简体   繁体   中英

jquery mouseenter do this, mouseleave do that, click do this and stop mouseenter/mouseleave events

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?.

Just turn off the mouseleave when you click with:

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

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');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM