user1998102
user1998102

Reputation:

jQuery click function affecting multiple divs

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).

Upvotes: 1

Views: 222

Answers (2)

pussmun
pussmun

Reputation: 143

$(".expand").click(function() {
        $(this).addClass("hovered");
        ..
    });

Upvotes: 0

isherwood
isherwood

Reputation: 61055

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");
    ...
});

Upvotes: 2

Related Questions