the_martux
the_martux

Reputation: 885

add and remove class to an id

When I click on the class show the 'id does not return the class hide Can you help me? Thanks

CSS

    .hide{color: red}
    .show{ color: green}

HTML

<div id="prova" class="hide">
    prova
</div>

jQuery

$(document).ready(function()
    {
        $("#prova.hide").click(function()
        {

            $(this).removeClass();
            $(this).addClass("show")
        })
        $("#prova.show").click(function()
        {

            $(this).removeClass();
            $(this).addClass("hide")
        })

    })

Upvotes: 1

Views: 24863

Answers (3)

James Montagne
James Montagne

Reputation: 78740

When $("#prova.hide").click( is called, the click function is only applied to those elements which match the selector at the time the code is run. You should instead do something like this:

$("#prova").click(function()
{
    var $this = $(this);

    if($this.hasClass("show")){
        $this.removeClass("show");
             .addClass("hide");
    } else {
        $this.removeClass("hide");
             .addClass("show");
    }
});

Upvotes: 0

palaѕн
palaѕн

Reputation: 73966

Try this:

$("#prova").click(function(){
    $(this).toggleClass('show hide');
});

DEMO HERE

Upvotes: 2

Schleis
Schleis

Reputation: 43790

Your click events are not bound when you change the class. So when you change the class, the elements do not have events associated with them anymore.

    $(document).on('click', "#prova.hide", function()
    {

        $(this).removeClass();
        $(this).addClass("show")
    })
    $(document).on('click', "#prova.show", function()
    {

        $(this).removeClass();
        $(this).addClass("hide")
    })

Upvotes: 1

Related Questions