cmplieger
cmplieger

Reputation: 7351

My "toggle class" javascript is not working

I am using this little script to toggle classes of an element on click of another element. Here is the stripped down code:

//Toggle comments
function togglecomments() {
    function shiftcomments() {
        var comments = document.getElementsByTagName('aside')[0];
        if(comments.className = "hide"){comments.className = "show";}
        else{comments.className = "hide";};
    }
    var commenttoggle = document.getElementById('toggle-comments');
    bindEvt(commenttoggle, "click", shiftcomments);


}
bindEvt(window, "load", togglecomments);

The thing is it works once, but after that on click the class does not toggle anymore. For those interested here is the event handler I use: http://pastebin.com/md3dPvMJ (It worked fine before so it shouldn't be the problem.)

Any ideas what I did wrong?

Thanks for your feedback guys!

Upvotes: 2

Views: 172

Answers (2)

Bitzu
Bitzu

Reputation: 133

This is a little function I'm using, with jQuery, but it can be updated.

        toggleClass = function (obj, className) {
            var currentClass = $(obj).attr('class'),
                hasIt = false;
            if (currentClass.indexOf(className) < 0) {
                currentClass += " " + className;
                hasIt = true;
            } else {
                currentClass = currentClass.replace(className, "");
                hasIt = false;
            }

            $(obj).attr('class', currentClass);
            return hasIt;
        };

Upvotes: 0

Paulo R.
Paulo R.

Reputation: 15609

In your if statements you've got this:

if(comments.className = "hide")

It should be:

if(comments.className === "hide") 

This would also work:

if(comments.className == "hide") 

What you are actually doing up there is changing the className to "hide", not checking for equality.

For the difference between == and === I'll actually point you to another question here at stackoverflow: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Upvotes: 1

Related Questions