How can I toggle the content div on/off when I click on the ‘toggle’ text?
<div class="toggle col">TOGGLE
<div class="content-to-toggle">
content
</div>
</div>
Is there a lighter version than this one:
document.addEventListener('click', function(e){
if(e.target.className.indexOf('toggle') !== -1)
e.target.className = e.target.className.replace(/\bexp\b|\bcol\b/, function(m){ return m == 'col' ? 'exp' : 'col'; });
});
?
That function has a few flaws:
e.targetwill fail in browsers like IE 8 and lowerindexOf('toggle')will matchtoggleanywhere in the class value, probablly better to use a regualr exprssion like: /(^|\s)toggle(\s|$)/replace(/\bexp\b|\bcol\b/uses word breaks as the delimiter, but class values are separated by spaces, not word breaks (like hyphen)Lastly, what do you mean by “ligther”? Less code? Faster? Uses fewer resources?
Edit
A better version of the function would use:
Also there should be a fork to say what to do if the element doesn’t have either of the classes—should it default to one or the other or do nothing?
So here’s an example:
Edit 2
“Less code” is never a good reason to do anything, though it is a reasonable objective where it doesn’t obfuscate or reduce clarity. In any case, here is a “better” version of your original:
It is a bit more efficient and uses a standard delimiter for class name values.