Richard Hedberg
Richard Hedberg

Reputation: 25

Add class to several elements

I have a cloned element and I want it so if I add a class to one of them it checks for active removes is and adds it to this and translates to the other. Here's what I'm working with:

$(document).ready(function() {


    $("li").click(function(){

        /*Here I want to add something like var active = $(.clonedelement + this, this)
        but that does probably not makes sense, so what should i do? */

        var active = $(this)

      // If this isn't already active
      if (!$(this).hasClass("active")) {
        // Remove the class from anything that is active
        $("li.active").removeClass("active");
        // And make this active
        active.addClass("active");

      }
    });


});

Right now, it removes the current active from both, not does only add class to one.

I made a jsfiddle of it http://jsfiddle.net/pintu31/8BxuE/

function UpdateTableHeaders() {
   $(".persist-area").each(function() {

       var el             = $(this),
           offset         = el.offset(),
           scrollTop      = $(window).scrollTop(),
           Header = $("#headerny", this)

       if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
          Header.addClass("floatingHeader");
       } else {
          Header.removeClass("floatingHeader");

       };
   });
}
// DOM Ready      
$(function() {

   $(window)
    .scroll(UpdateTableHeaders)
    .trigger("scroll");

});

Upvotes: 0

Views: 83

Answers (3)

Pragnesh Chauhan
Pragnesh Chauhan

Reputation: 8476

try this

demo updated 1
demo updated 2 //with clone(true)
demo updated 3 //with clone(false) - default
demo updated 4

 $(document).ready(function() {
    $(document).on('click', 'li', function(){
        var ind = $(this).index();
        $('li').removeClass('active');
        $('li').eq(ind).addClass('active');
        $('#header1').empty();
        $('#header').find('ul').clone(true).appendTo( '#header1' );
    });
});

Upvotes: 1

afei
afei

Reputation: 11

$(document).ready(function() {


    $("li").click(function(){
        $("li").removeClass("active");
        // And make this active
        $(this).addClass("active");

      }
    });


});

Upvotes: 0

Pat Dobson
Pat Dobson

Reputation: 3299

If you just need to highlight the clicked element with the class of active, and remove all others then try this:

$("li").click(function(){
    $("li").removeClass("active");
    $(this).addClass("active");
  });

You don't really need to check if either this, or others already have the class, simply steamroller to 'active' class off all the others and add it to the one that's been clicked

Upvotes: 1

Related Questions