Reputation: 8264
I'm manipulating image source with this code below, works great, but I'm failing to add a mouseout function (so when not hovering over one of the specified <li>
) the image source of the one being changed in the code below, returns to how it was before any hover took place, any thoughts?
window.addEventListener('load', function() {
var imageContainer = document.querySelectorAll('.image_left')[0];
function initImageHover(selector) {
var elements = document.querySelectorAll(selector);
console.log(elements);
for (var i = 0, len = elements.length; i < len; i++) {
createHover(elements[i]);
};
}
function createHover(that) {
that.addEventListener('mouseover', function() {
var src = that.getAttribute('data-src');
if (src) {
imageContainer.src = src;
}
});
that.addEventListener('mouseleave', function() {
imageContainer.src = '';
});
}
initImageHover('li.one > a');
});
window.addEventListener('load', function() {
var imageContainer = document.querySelectorAll('.image_left2')[0];
function initImageHover(selector) {
var elements = document.querySelectorAll(selector);
console.log(elements);
for (var i = 0, len = elements.length; i < len; i++) {
createHover(elements[i]);
};
}
function createHover(that) {
that.addEventListener('mouseover', function() {
var src = that.getAttribute('data-src');
if (src) {
imageContainer.src = src;
}
});
that.addEventListener('mouseleave', function() {
imageContainer.src = '';
});
}
initImageHover('li.two > a');
});
Update the original image; is outside of the li elements, and is in the mark-up like below. Currently just getting image null / dead images with two answered attempts.
<div class="block2wrap">
<div class="left">
<article class="left_image">
<img src="images/verycoolimage.jpg" class="image_left">
</article>
Upvotes: 0
Views: 191
Reputation: 11656
Save the original image src in a variable and use it when the mouse leaves:
function createHover (that) {
var original = that.getAttribute('src');
that.addEventListener('mouseover', function() {
var src = that.getAttribute('data-src');
if (src) {
imageContainer.src = src;
}
});
that.addEventListener('mouseleave', function() {
imageContainer.src = original;
});
}
Here is a fiddle.
Upvotes: 3
Reputation: 919
add this lines to the mouseover function (before you set the src)
var _src = that.getAttribute('src');
that.setAttribute('data-old-src', _src);
Change this line in mouseleave
imageContainer.src = '';
to that
imageContainer.src = that.getAttribute('data-old-src');
Upvotes: 1