user3143218
user3143218

Reputation: 1816

JavaScript Single Click Function On Each Element

I'm working on a simple click/toggle function with JavaScript. I have multiple buttons that run the same function that changes its color when clicked. I want the color to be toggled for each button though.

So far it looks like this:

HTML

<button class="button red">button</button>
<button class="button yellow">button</button>
<button class="button green">button</button>
<button class="button blue">button</button>

CSS

.button {
    background:black;
    text-decoration:none;
    border-radius:6px;
    color:white;

}
.red     {background:red}
.yellow  {background:yellow}
.blue    {background:blue;}
.green   {background:green;}
.magenta {background:magenta !important;}

JS

// hasClass
function hasClass(elem, className) {
    return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');
}
// toggleClass
function toggleClass(elem, className) {
    var newClass = ' ' + elem.className.replace( /[\t\r\n]/g, " " ) + ' ';
    if (hasClass(elem, className)) {
        while (newClass.indexOf(" " + className + " ") >= 0 ) {
            newClass = newClass.replace( " " + className + " " , " " );
        }
        elem.className = newClass.replace(/^\s+|\s+$/g, '');
    } else {
        elem.className += ' ' + className;
    }
}
document.querySelector('.button').onclick = function() {
    toggleClass(this, 'magenta');
}

and the fiddle : http://jsfiddle.net/S3K3c/

Upvotes: 0

Views: 275

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324730

Are you a jQuery user by any chance? $(".button").click(function(){...}); does a lot more under the hood than you think.

Try this:

[].forEach.call(document.querySelectorAll(".button"),function(btn) {
    btn.onclick = function() {this.classList.toggle("magenta");}
});

Upvotes: 2

Related Questions