Search code examples
jquerycsshovercursortoggle

jquery change cursor on hover and click


I'm using an image zoomer and I need 2 different mouse states on hover.

#1 On hover of the containing <div> the cursor becomes a 'plus' symbol.
#2 When the user clicks the cursor changes to a 'minus' symbol. (now zoomed in)
#loop Once clicked again the cursor goes back to the plus symbol (default hover-view)

I can't use mousedown/up or :active because I need it to stay until clicked again,
so I think using toggle is my best bet.

So far I've got this http://jsfiddle.net/fCe9B/ but it doesn't work quite right.
Depending on where the default hover image-call is placed, either the toggle won't replace the hover or vice versa.
As long as I can get both cursor states to appear I should be good.
Can anyone help me solve this?

CSS

.cursor {cursor:move;}
#box {height:300px;width:300px;background:blue;}
#box:hover {cursor:help;}

Jquery

$(document).ready(function(){
$("#box").click(function(){
$("#box").toggleClass("cursor");
});
});

Solution

  • You could do something like this where you check if the images has a certain css class that changes the cursor.

       $(document).ready(function(){
    
          $(".box").hover(function(){
            if($(this).hasClass("zoomed")){
              $(this).removeClass("zoomed");
            }else{
              $(this).addClass("zoomed");
          } 
        });
      $(".box").click(function(){
          if($(this).hasClass("zoomed")){
            $(this).removeClass("zoomed");
          }else{
              $(this).addClass("zoomed");
    
          }
      });
    });
    

    CSS

    .box {
        height:300px;
        width:300px;
        background:blue;
        cursor:w-resize;
    }
    
    
    .zoomed{
        cursor:crosshair;
    }
    

    HTML

    <div class="box"></div>
    

    Heres the jsfiddle so you can try it. http://jsfiddle.net/fCe9B/9/