jQuery multiple class selection

Posted by morpheous on Stack Overflow See other posts from Stack Overflow or by morpheous
Published on 2010-04-26T07:59:19Z Indexed on 2010/04/26 8:03 UTC
Read the original article Hit count: 215

Filed under:

I am a bit confused with this:

I have a page with a set of buttons (i.e. elements with class attribute 'button'. The buttons belong to one of two classes (grp1 and grp2).

These are my requirements

  • For buttons with class enabled, when the mouse hovers over them, a 'button-hover' class is added to them (i.e. the element the mouse is hovering over). Otherwise, the hover event is ignored

  • When one of the buttons with class grp2 is clicked on (it has to be 'enabled' first), then I disable (i.e. remove the 'enabled' class for all elements with class 'enabled' (should probably selecting for elements with class 'button' AND 'enabled' - but I am having enough problems as it is, so I need to keep things simple for now).

This is what my page looks like:

<html>
<head>
   <title>Demo</title>
   <style type="text/css"
     .button {border: 1px solid gray; color: gray}
     .enabled {border: 1px solid red; color: red}
     .button-hover {background-color: blue; }
   </style>
   <script type="text/javascript" src="jquery.js"></script>
</head>
<body>
   <div class="btn-cntnr">
      <span class="grp1 button enabled">button 1</span>
      <span class="grp2 button enabled">button 2</span>
      <span class="grp2 button enabled">button 3</span>
      <span class="grp2 button enabled">button 4</span>
   </div>
   <script type="text/javascript">
      /* <![CDATA[ */
      $(document).ready(function(){

        $(".button.enabled").hover(function(){
            $(this).toggleClass('button-hover');
          }, function() {
            $(this).toggleClass('button-hover');
        });

        $('.grp2.enabled').click(function(){ $(".grp2").removeClass('enabled');}
       });      
      /* ]]> */
   </script>
</body>
</html>

Currently, when a button with class 'grp2' is clicked on, the other elements with class 'grp2' have the 'enabled' class removed (works correctly).

HOWEVER, I notice that even though the class no longer have a 'enabled' class, SOMEHOW, the hover behaviour is still applied to these elemets (WRONG). Once an element has been 'disabled', I no longer want it to respond to the hover() event.

How may I implement this behavior, and what is wrong with the code above (i.e. why is it not working? (I am still learning jQuery)

© Stack Overflow or respective owner

Related posts about jQuery