Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to add mouseleave, mouseenter and click event using jQuery

    • 1
    • 0
    • 0
    • 3
    • 0
    • 0
    • 0
    • 2.38k
    Answer it

    Hello,

    I want to change the image when entering and leaving mouse to it. But the image should stay there when clicked. I have an image attribute source that is replaced on mouse enter and mouse leave event. But image is also changing after clicking. I need the mouseleave event to stop working after clicking the image. Here is the code below:

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

 3 Answer(s)

  • Hi Swati,

    You have to set a global boolean variable Flag before changing your image source. Like this:

    $(document).ready(function(){
        var flag = true;
        $('.imgContainer').mouseenter(function(){
            if (flag) {
                 $('.imgContainer').attr('src','img1.gif');
             }
         }),
        $('.imgContainer').mouseleave(function(){
            if (flag) {
                  $('.imgContainer').attr('src','img2.gif');
            }
        }),
        $('.imgContainer').click(function(){
           flag = false;
         }); });
    
Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: