Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery change CSS class on clicking

I am working on a project i am having some anchors like tab, each have some CSS class, the selected tab have separate css class. I am clicking on tab and i want to change its CSS class to selected css class i have done this functionality but i am having some problems with it is that previously selected tab also having same class, how can i change the previous selected tab to unselected class,Below is my code

$(".btn").each(function ()
{
    $(this).click(function () {                              
        $(this).removeClass("course-btn-tab").addClass("course-btn-tab-selected");        
    });
});

<div class="course-Search-tabs">
    <a href="#" class="course-btn-tab-selected btn" id="a">A</a>
    <a href="#" class="course-btn-tab btn" id="b">B</a>
    <a href="#" class="course-btn-tab btn" id="c">C</a>
    <a href="#" class="course-btn-tab" id="d">D</a>
</div>
like image 707
Syed Salman Raza Zaidi Avatar asked Jan 08 '13 10:01

Syed Salman Raza Zaidi


3 Answers

You do not need to use each here, on click of element with class btn remove class for all elements with class btn and assign the desired class to current element (referred by $(this)) which is event source. Also I assume you want to remove selected class from previous elements.

$(".btn").click(function () { 
     if($(this).hasClass("course-btn-tab-selected"))
          $(".btn").removeClass("course-btn-tab-selected").addClass("course-btn-tab");               
     $(this).addClass("course-btn-tab-selected");        
});

Edit: You can improve this by hold the last selected element and changing it class if it suits you.

previouslyClicked = $(".btn").eq(0); //Assuming first tab is selected by default
$(".btn").click(function () {       
     previouslyClicked.removeClass("course-btn-tab-selected").addClass("course-btn-tab");                 
     $(this).addClass("course-btn-tab-selected");
     previouslyClicked = $(this);           
});
like image 178
Adil Avatar answered Oct 27 '22 00:10

Adil


Wrong usage of $.each()

Use this way:

$(".btn").click(function () {
    $(".btn").removeClass("course-btn-tab-selected");
    $(this).addClass("course-btn-tab-selected");        
});
like image 30
Praveen Kumar Purushothaman Avatar answered Oct 26 '22 23:10

Praveen Kumar Purushothaman


Should do the trick:

$(".btn").click(function () { 
        $(".course-btn-tab-selected").removeClass("course-btn-tab-selected").addClass('course-btn-tab');                 
        $(this).removeClass('course-btn-tab').addClass("course-btn-tab-selected");        

    });
like image 39
A. Wolff Avatar answered Oct 27 '22 01:10

A. Wolff