2

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!

cmplieger
  • 7,155
  • 15
  • 55
  • 83

2 Answers2

1

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?

Community
  • 1
  • 1
João Paulo Macedo
  • 15,297
  • 4
  • 31
  • 41
0

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;
        };
Bitzu
  • 125
  • 2
  • 11
  • The problem with index of would be that it doesn't stop on words. Example: HTML: `
    `. If you call toggleClass with `className=clazz` the `indexOf` would return >=0 and this would result in `
    `.
    – Alexander Jun 26 '15 at 08:51
  • That is if you don't namespace your classes. – Bitzu Jun 26 '15 at 13:00