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.53k
    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:

    1. <script>
    2. $('.imgContainer').mouseenter(function(){
    3. $('.imgContainer').attr('src','http://url-to-my-active-image.jpg');
    4. }),
    5. $('.imgContainer').mouseleave(function(){
    6. $('.imgContainer').attr('src','http://url-to-my-inactive-image.jpg');
    7. }),
    8. $('.imgContainer').click(function(){
    9. $('.imgContainer').css('opacity','1');
    10. });
    11. </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
Reset Password
Fill out the form below and reset your password: