StuBlackett
StuBlackett

Reputation: 3857

Target specific div in jQuery

I am trying to make my code more efficient. So I am trying to use the same line of jQuery to create a toggle.

I have got this working for 1 item on my page.

The problem I have is when clicking the second item that is to slide down, It is sliding the first element down.

I have created a jsFiddle. to demo my issue.

and my jQuery is as follows....

// Accordion Related....
    $('h3.accordion-header').click(function()
    {
        $('.accordion').children().eq(1).slideToggle(function ()
        {
            $('h3.accordion-header').toggleClass('active', $(this).is(':visible'));
        });

        return false; // Prevent Default Click..

    })

I am wondering how do I target that specific class of accordion not the first on the page. If its at all possible?

Thanks

Upvotes: 0

Views: 839

Answers (3)

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

The code could capture the event at the accordion level. Then the other selections can be scoped more easily.

$(".accordion").on("click", ".accordion-header", function()
{
    var that = this;
    $(".row", $(this).parents(".accordion")).slideToggle(function ()
    {
        $(that).toggleClass('active',  $(this).is(':visible'));
    });

    return false; // Prevent Default Click..
});

Js Fiddle: http://jsfiddle.net/Y3mKA/8/

Upvotes: 1

bipen
bipen

Reputation: 36541

use this reference and closest()..

// Accordion Related....
$('h3.accordion-header').click(function () {
   $(this).closest('.accordion').children().eq(1).slideToggle(function () {
 //^^^^^^^^^^^^^^^^-----here 
     $(this).toggleClass('active', $(this).is(':visible'));
   });


   return false; // Prevent Default Click..

})

fiddle here

or easiest would be usign next()..(if you are sure the elements is always next to the h3 element)

 $('h3.accordion-header').click(function () {
   $(this).next().slideToggle(function () {
      $(this).toggleClass('active', $(this).is(':visible'));
   });
     return false; // Prevent Default Click..
  });

fiddle using next()

Upvotes: 2

Praxis Ashelin
Praxis Ashelin

Reputation: 5217

With $(".accordion")you are selecting all accordion elements, not just the one inside the element you clicked. The same happens when setting the active class.

This code will work:

// Accordion Related....
    $('h3.accordion-header').click(function()
    {
        var currentClicked = $(this);
        currentClicked.parent().find(".row").slideToggle(function ()
        {
            currentClicked.toggleClass('active', $(this).is(':visible'));
        });

        return false; // Prevent Default Click..

    })

Fiddle: http://jsfiddle.net/Y3mKA/4/

Upvotes: 1

Related Questions