Hover Over A Tag Class Change Image Src Of Img In Different Element
Say I have something like this:
Solution 1:
You could add event listeners for mouseover & mouseleave and then change the image.src accordingly, like in such a way
window.addEventListener('load', function() {
function initImageHover(selector, displaySelector) {
var imageContainer = document.querySelectorAll(displaySelector)[0],
elements = document.querySelectorAll(selector);
for (var i = 0, len = elements.length; i < len; i++) {
createHover(elements[i], imageContainer, imageContainer.src);
};
}
function createHover(that, targetElement, originalImage) {
that.addEventListener('mouseover', function() {
var src = that.getAttribute('data-src');
if (src) {
targetElement.src = src;
}
});
that.addEventListener('mouseleave', function() {
targetElement.src = originalImage;
});
}
initImageHover('li > a', '.image_left');
});
<div class="right">
<article class="left_image">
<img src="images/coolestimageontheplanet.jpg" class="image_left">
</article>
<ul class="LISTS">
<li><a href="#link" target="_blank" class="hov1">Link 1</a>
</li>
<li><a href="#link" target="_blank" class="hov2">Link 2</a>
</li>
<li><a href="#link" target="_blank" class="hov3">Link 3</a>
</li>
<li><a href="#link" target="_blank" class="hov4">Link 4</a>
</li>
<li><a href="#link" target="_blank" class="hov5">Link 5</a>
</li>
<li><a href="#link" target="_blank" class="hov6">Link 6</a>
</li>
<li><a href="#link" target="_blank" data-src="http://cdn.sstatic.net/stackoverflow/img/sprites.svg?v=a7723f5f7e59" class="hov7">Link 7</a>
</li>
</ul>
Solution 2:
Add a data tag like so:
<ul class="LISTS">
<li><a href="#link" target="_blank" class="hov5" data-img="images/newimg.jpg">Link 1</a></li>
<!-- etc -->
Then use a code like this:
$("ul.LISTS>li").hover(function(){
var imgurl = $(this).data("img");
$(".image_left").attr("src",imgurl);
},
function(){
$(".image_left").attr("src","images/coolestimageontheplanet.jpg");
});
Post a Comment for "Hover Over A Tag Class Change Image Src Of Img In Different Element"