I'm using this code to change opacity when user is on and off a picture unfortunately when the user clicks the image the opacity does not stay at 1. Anyone has an answer ?
$(document).ready(function(){
$('img#slide').animate({"opacity" : .7})
$('img#slide').hover(function(){
$(this).stop().animate({"opacity" : 1})
}, function(){
$(this).stop().animate({"opacity" : .7})
});
$('img#slide').click(function(){
$(this).animate({"opacity" : 1});
});
});
You need to somehow disable the mouseleave animation when the user clicks.
A common approach is to add a class, and have the mouseleave check for the existence of the class.
Test the live example: http://jsfiddle.net/KnCmR/
$(document).ready(function () {
$('img#slide').animate({ "opacity": .7 })
.hover(function () {
$(this).stop().animate({ "opacity": 1 })
},
function () {
if ( !$(this).hasClass("active") ) {
$(this).stop().animate({ "opacity": .7 });
}
})
.click(function () {
$(this).addClass("active");
});
});
EDIT:
If you want a second click to revert the behavior back to the original, use toggleClass() instead of addClass():
$(this).toggleClass("active");
jQuery docs:
.hasClass() - http://api.jquery.com/hasClass.addClass() - http://api.jquery.com/addClass.toggleClass() - http://api.jquery.com/toggleClassIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With