Pregunta

I am trying to have an image attribute source replaced on mouse enter mouse leave event. And when clicked, the image should stay as active. I need the mouseleave event to stop after clicking has been made. So far the mouseeleave still continues after clicking, switching back the image , here is the code below:

<script>
    jQuery('.paypal').mouseenter(function(){
        jQuery('.paypal').attr('src','http://url-to-my-active-image.jpg');?>');
    }),
    jQuery('.paypal').mouseleave(function(){
        jQuery('.paypal').attr('src','http://url-to-my-inactive-image.jpg');
    }),
    jQuery('.paypal').click(function(){
        jQuery('.paypal').css('opacity','1');
    });
</script>

How can I achieve that?.

¿Fue útil?

Solución

Just turn off the mouseleave when you click with:

jQuery('.paypal').click(function(){
    jQuery('.paypal').css('opacity','1').off('mouseleave');
});

Otros consejos

A quick solution seems to be to add a class on click, and then check for the presence of that class on mouseleave; if it's there, do nothing.

<script>
    jQuery('.paypal').mouseenter(function(){
        jQuery('.paypal').attr('src','http://url-to-my-active-image.jpg');?>');
    }),
    jQuery('.paypal').mouseleave(function(){
        if(!jQuery('.paypal').hasClass('selected')){
            jQuery('.paypal').attr('src','http://url-to-my-inactive-image.jpg');
        }
    }),
    jQuery('.paypal').click(function(){
        jQuery('.paypal').css('opacity','1').addClass('selected');
    });
</script>

@j08691's answer is probably easier to maintain, especially if you're using a recent version of jQuery (1.7 or higher).

You can turn off the mouseleave handler inside the click handler by using off:

jQuery('.paypal').click(function() {
    jQuery('.paypal').css('opacity', '1');
    jQuery('.paypal').off('mouseleave');
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top