Reputation: 257
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?
Upvotes: 0
Views: 243
Reputation: 815
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?
Upvotes: 0
Reputation: 1074108
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.
Upvotes: 1