How can I simplify this into one single function:
$("#tab-one").click(function() {
var imageUrl = "img/img-1.png";
$(".masthead.product-detail").css("background-image", "url(" + imageUrl + ")");
});
$("#tab-two").click(function() {
var imageUrl = "img/img-2.png";
$(".masthead.product-detail").css("background-image", "url(" + imageUrl + ")");
});
$("#tab-three").click(function() {
var imageUrl = "img/img-3.png";
$(".masthead.product-detail").css("background-image", "url(" + imageUrl + ")");
});
Many thanks in advance!
2
Answers
add corresponding image
src
to each tab as a data-* attribute.Give a common class to all tabs.
Now you can reduce your code with one click handler like below:
Sample working snippet:
You can code like this:
In your HTML use
data-*
attribute:Then in your JavaScript Code:
This is how using
data-*
attribute, simply you can change the background image.