superUntitled
superUntitled

Reputation: 22547

jQuery: remove class once element is clicked

I am stuck on a little jQuery problem. I have a collection of links (more than 50) generated from a php loop. When a user clicks on a link, the jQuery load event is called, and a php/mysql script (called page.php in the example below) is loaded into an empty div on the page.

I would like the class (".classy") to removed from the < a > tag and replaced with another class (".newclass"). This is so that the information is loaded only on the first click.

The html:

<a class='classy' name='marvin'>Click to toggle info</a>
<div id='marvin'></div>

The jQuery:

$(document).ready(function(){
    $(".classy").click(function(){
        var foo = $(this).attr("name");
        $("#"+foo).load("page.php?id="+foo).slideToggle('fast'); 
        $(this).removeClass('classy');
        $(this).addClass('newclass');
        return false;
    });
});

Thanks!

Upvotes: 1

Views: 481

Answers (2)

Drew Wills
Drew Wills

Reputation: 8446

Not positive -- but you may need to do it like this (use $.live()) instead:

$(document).ready(function(){
    $(".classy").live('click', function(){
        var foo = $(this).attr("name");
        $("#"+foo).load("page.php?id="+foo).slideToggle('fast'); 
        $(this).removeClass('classy').addClass('newclass');
        return false;
    });
});

Upvotes: 1

Marek Karbarz
Marek Karbarz

Reputation: 29314

Just because you change the class doesn't mean the click event handler is removed from the link. You will need to unbind it manually or just add an if statement that checks what class the link has.

Or use live function to bind the click event.

Upvotes: 2

Related Questions