Changing Image With Onclick From An Unordered List Of Images (colours)
this is my first question here so I hope i'm as clear as I can be. I'm creating a product page and have an unordered list of images that represent various colours that a product c
Solution 1:
Here is a totally different approach but I believe offers a much clear solution:
<!doctype html>
<html>
<head>
<title>Test code</title>
</head>
<body>
<div>
<img src="http://mlb-s1-p.mlstatic.com/camiseta-personalizada-com-smiles-ideogramas-simbolos-13992-MLB3293421990_102012-O.jpg">
<ul>
<li data-src="http://mlb-s1-p.mlstatic.com/camiseta-personalizada-com-smiles-ideogramas-simbolos-13992-MLB3293421990_102012-O.jpg">Yellow</li>
<li data-src="http://images.clipartof.com/thumbnails/67235-Royalty-Free-RF-Clipart-Illustration-Of-A-Happy-Blue-Emoticon-Face-Smiley.jpg">Blue</li>
<li data-src="http://www.cliparthut.com/clip-arts/169/green-smiley-face-clip-art-169032.png">Green</li>
</ul>
</div>
<script>
document.addEventListener("click", function(e) {
var target = e.target;
// If not one of the `li` items, ignore it
if (!target.tagName.toLowerCase() === "li") {
return;
}
// If it doesn't have a data-src, ignore it
var newSrc = target.getAttribute("data-src");
if (!newSrc) {
return;
}
// IN this case, we know exactly how the DOM is layed out
// and that the parent we want is two levels up.
// Looping through this is sometimes a better idea.
var parentDiv = target.parentNode.parentNode;
var img = parentDiv.getElementsByTagName("img")[0];
console.log(img);
img.src = newSrc;
});
</script>
</body>
</html>
Post a Comment for "Changing Image With Onclick From An Unordered List Of Images (colours)"