How can I turn this piece of jQuery code into JavaScript?
$('#element').click(function(){
$(this).toggleClass('class1 class2')
});
I have already tried the following pieces of code, but to no avail.
First one is:
var element = document.getElementById('element'),
classNum = 0; // Supposing I know that the first time there will be that class
element.onmousedown = function() {
if (classNum === 0) {
this.classList.remove("class1");
this.classList.add("class2");
classNum = 1;
}
else if (classNum === 1) {
this.classList.remove("class2");
this.classList.add("class1");
classNum = 0;
}
}
Second one is:
var element = document.getElementById('element'),
classNum = 0; // Supposing I know that the first time there will be that class
element.onmousedown = function() {
if (classNum === 0) {
this.className -= "class1";
this.classList += "class2";
classNum = 1;
}
else if (classNum === 1) {
this.classList -= "class2";
this.classList += "class1";
classNum = 0;
}
}
Any answer that doesn't suggest that I stick with jQuery will be greatly appreciated.
[EDIT]
I've tried all of your solutions, but haven't been able to get it right. I believe it's because I didn't state clearly that the element has multiple classes like so:
class="class1 class3 class4"
And what I want is basically to replace class1 with class2 and toggle between them.
JavaScript Toggle Class Multiple Elements You can also toggle class on multiple element at once. For this target multiple elements and use the toggle() method. To toggle a class on multiple elements select those elements and apply the toggle method on each element to handle their corresponding class.
The toggleClass() method toggles between adding and removing one or more class names from the selected elements. This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect.
Toggle Class Toggle between adding a class name to the div element with id="myDIV" (in this example we use a button to toggle the class name).
Answer. Yes, you can toggle multiple classes using a single . toggleClass() call. To do so, you can separate the class names with spaces.
Update: In response to comments, classList.toggle is a pure javascript solution. It has nothing to do with jQuery as one comment implies. If there is a requirement to support old versions of IE then there is a shim (pollyfill) at the MDN link below. And this shim, if needed, is far superior to the accepted answer.
Using classList.toggle certainly seems like the simplest solution. Also see Can I Use classList for browser support.
element.onclick = function() {
'class1 class2'.split(' ').forEach(function(s) {
element.classList.toggle(s);
});
}
Run the snippet to try
box.onclick = function() {
'class1 class2'.split(' ').forEach(function(s) {
box.classList.toggle(s);
stdout.innerHTML = box.className;
});
}
/* alternative
box.onclick = function() {
['class1', 'class2'].forEach(function(s) {
box.classList.toggle(s);
stdout.innerHTML = box.className;
});
}
*/
.class1 { background-color: red;}
.class2 { background-color: blue;}
.class3 { width: 100px; height: 100px; border: 1px black solid;}
click me:
<div id="box" class="class1 class3"></div>
<div id="stdout"></div>
classNum
is a local variable.
Every time the event handler is called, you get a new variable, which has nothing to do with the value from the last call.
You want that to be a global variable.
Or, better yet, check classList.contains
instead.
From: You might not need jQuery
$(el).toggleClass(className);
Is replaced by:
if (el.classList) {
el.classList.toggle(className);
} else {
var classes = el.className.split(' ');
var existingIndex = classes.indexOf(className);
if (existingIndex >= 0)
classes.splice(existingIndex, 1);
else
classes.push(className);
el.className = classes.join(' ');
}
Then simply wrap that function call within a document.getElementById('elementId').click
See fiddle: https://jsfiddle.net/2ch8ztdk/
var s = document.getElementById('element');
s.onclick=function(){
if(s.className == "class1"){
s.className = "class2"
} else {
s.className = "class1"
}
}
Your code is close, but your classNum variable isn't iterative. Try this:
var element = document.getElementById("element");
var numCount = 0;
element.addEventListener('click', function() {
if (numCount === 0) {
this.className = "";
this.className += " class1";
numCount++;
} else {
this.className = "";
this.className += " class2";
numCount = 0;
}
});
.class1 {
color: red;
}
.class2 {
color: blue;
}
<div id="element">click me</div>
you can use classList
, but it only support IE 10+
Demo
var eles = document.querySelectorAll('#element');
var classNames = 'one two';
for(var i = 0; i < eles.length; i ++){
eles[i].onclick = function(e){
toggleClass.call(this, classNames);
}
}
function toggleClass(names){
var sp = names.split(' ');
for(var i = 0; i < sp.length; i++){
this.classList.toggle(sp[i]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With