1

I'm trying to use jQuery's click function to apply a hover state to a selected div, without differentiating the div's in the JavaScript. I'm currently using:

 $(document).ready(function(){
    $(".project").click(function() {
            $("a.expand").removeClass("hovered");
            $("a.expand").addClass("hovered");
            $(".project_full").hide();
            var selected_tab = $(this).find("a").attr("href");
            $(selected_tab).fadeIn();
            return false;
        });

With the HTML:

<div class="project first project_gizmoscoop">
  <div class="title">
     GizmoScoop!                    
     <div class="date">2012</div>
  </div>
  <a class="expand" title="(Caption)" href="#project_1">GizmoScoop!</a>
</div>
<div class="project project_sc">
  <div class="title">
     Striking Code                  
     <div class="date">2011</div>
  </div>
  <a class="expand" title="(Caption)" href="#project_2">Striking Code</a>
</div>

The .hovered class is applied to the clicked link (specific styles from an external CSS file). However, everything is being chosen. (See http://www.codeisdna.com for an example).

I know what I'm doing wrong (I should be specifying the individual ID's or using HTML5 data attributes), but I'm stuck unnecessarily. I feel like a complete newb right now, that I can't do something this simple (although I've done more advanced stuff).

1
  • You're both adding and removing the same class (.hovered) in your example code, by the way. Commented Mar 13, 2013 at 19:04

2 Answers 2

2

You simply need to take advantage of jQuery's flexibility (and good programming practice) and reduce your scope accordingly. You're already doing something similar with your variable definition. For example, to target only those a.expand elements inside the instance of .project that's clicked:

$(".project").click(function() {
    $(this).find("a.expand").removeClass("hovered");
    ...
});
Sign up to request clarification or add additional context in comments.

1 Comment

You're right! I applied $(this) to the action of adding the class (kept .removeClass as it was) and everything works great! I knew it was something small, but I just couldn't think of this! Thanks!
0
$(".expand").click(function() {
        $(this).addClass("hovered");
        ..
    });

1 Comment

The code didn't work too well for me! It applied each individually, but following isherwood's example provided a cleaner way for me to disable the clicks (and keep the tabs intact).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.