I'm having a trouble with changing images with jQuery. I have following markup:
<div class="row">
<img src="image.png" class="download-image regular-image" />
<div class="options">
<p>download</p>
</div>
<img src="image.png" class="download-image regular-image" />
<div class="options">
<p>download</p>
</div>
</div>
and following code to manipulate this markup:
$('.regular-image').hover(function() {
$(this).attr('src', 'image2.png');
}. function() {
$(this).attr('src', 'image.png');
}
This code is pretty straightfoward and I have no problem with it but lately I introduced another function to keep active image (i.e one that shows up if element is clicked):
$('.download-image').click(function(e) {
e.stopPropagation();
$(this).next().toggle();
$('.download-image').removeClass('current');
$(this).addClass('current');
if ($('.download-image').hasClass('current')) {
$(this).hover(function() {
$(this).attr('src', 'image2.png');
}, function() {
$(this).attr('src', 'image2.png');
}
}
}
Idea behind this chunk is simple - I added a current class to track what element is being active at the moment and then make its element image to stay the same on hover and mouse out using image2.png which represents active state. It works but when I click on another element, previously clicked element doesn't behave like a regular one (i.e it keeps image2.png attribute on hover and mouse out instead of acting like it was coded for .regular-image class). What I did wrong? I feel like solutio might be stupidly easy and straightforward but I can't find it by myself. Any help or thoughts will be highly appreciated!
Thank you for dedicating you time and have a nice day.
UPD
To summarize my post, what I want to reach at the moment is to change image2.png back to image.png when other image is clicked and make it behave like described .regular-image in javascript code (to change it to image2.png while hovering and image.png while mouse is out)
UPD 2
With fellow devs' help I'm almost got behavior I want. I changed click event to this:
$(".download-image").click(function (event) {
event.stopPropagation();
$(this).next().toggle();
$('.download-image').removeClass('current');
$(this).addClass("current");
$(document).delegate('.current','mouseover',function() {
$(this).attr("src", "/image2.png");
});
$(document).delegate('.current','mouseout',function() {
$(this).attr("src", "/image2.png");
});
});
It works but only when I explicitly hover and mouse out on image, but I need to change image2.png back to image.png every time when I click on other image.