0

I have this great function which toggles class with pure javascript just like i want to:

// 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.getElementById('button').onclick = function() {
    toggleClass(this, 'active');
}

I tried to convert it to inline onclick function by removing this part:

document.getElementById('button').onclick = function() {
    toggleClass(this, 'active');
}

And adding:

onclick="toggleClass(this, 'active')"

To my element, but i guess i'm doing something wrong and it doesn't function at all.

Any ideas?

Ben
  • 257
  • 1
  • 15
  • *"...it doesn't function..."* is quite vague. What error(s) do you get? Have you looked in the web console? – T.J. Crowder Jun 21 '15 at 11:45
  • 3
    Why do you want inline function? It is bad practice. And `onclick` as well. Look into `addEventListener`, that's the proper modern way of attaching events. – elclanrs Jun 21 '15 at 11:47
  • The reason i want inline function is i want to use the same function on a lot of different elements. i think it's easier that way? am i wrong? – Ben Jun 21 '15 at 11:52
  • If you want to use the same function on a lot of different elements, then thats a lot easier to do the first way: just use a loop. You have to be careful about scope, but it's way better than copying-and-pasting the attribute string zillions of times in the HTML – Mark Reed Jun 21 '15 at 11:57
  • Seems to be working fine http://jsbin.com/genimo/3/edit – Eugene Jun 21 '15 at 11:59
  • Seems like what you need is event delegation. – elclanrs Jun 21 '15 at 12:11
  • Oh Thanks Eugene. that's weird it wasn't working in jsfiddle for some reason... Great! Thanks! – Ben Jun 21 '15 at 12:25

2 Answers2

1

At a guess, toggleClass isn't a global. onXyz attribute event handlers can only access global functions. It's one of the several reasons not to use them.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

What you are looking for is called closures: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#Creating_closures_in_loops.3A_A_common_mistake

Also this topic might be useful: How to generate event handlers with loop in Javascript?

Community
  • 1
  • 1
Mathijs Rutgers
  • 785
  • 4
  • 20