2

I am trying to add and remove class using jquery click function. It works for the first click but I don't know why it is not working for the second click. It not showing any errors as well.

Here is the html

<p class="right hand hidesubcategory">Hide</p>

And the script:

$('.hidesubcategory').click(function() {   
        $(this).text('Show');
        $(this).removeClass('hidesubcategory').addClass('showsubcategory'); 
});

$('.showsubcategory').click(function() {
        $(this).text('Hide');
        $(this).removeClass('showsubcategory').addClass('hidesubcategory');
});

Thanks in advance

0

3 Answers 3

2

At the time of binding, there was no element with class .showsubcategory, hence that binding never takes place.

With dynamic elements/bindings you need to update the code like following.

$(document).on('click', '.hidesubcategory', function() {   
        $(this).text('Show');
        $(this).removeClass('hidesubcategory').addClass('showsubcategory'); 
});

$(document).on('click', '.showsubcategory', function() { 
        $(this).text('Hide');
        $(this).removeClass('showsubcategory').addClass('hidesubcategory');
});

For reference - http://plnkr.co/edit/zCkzsnUmDXqV7cmvtP9g?p=preview

Sign up to request clarification or add additional context in comments.

Comments

2
$(function(){
 $(document).on('click', 'p.right.hand', function() {   
        var thisItem = $(this);

        if(thisItem.text() == 'Hide'){
          thisItem.text('Show');
        } else {
          thisItem.text('Hide');
        }

        if(thisItem.hasClass( "hidesubcategory" )){
          thisItem.removeClass('hidesubcategory').addClass('showsubcategory');
        } else {
          thisItem.removeClass('showsubcategory').addClass('hidesubcategory');
        }


});
});

Comments

1

Try this code.

$(document).ready(function() {
    $('.hidesubcategory').live("click",function () {
        $(this).text('Show');
        $(this).removeClass('hidesubcategory').addClass('showsubcategory');
    });

    $('.showsubcategory').live("click", function () {
        $(this).text('Hide');
        $(this).removeClass('showsubcategory').addClass('hidesubcategory');
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.