Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a div tag toggle between two css classes [duplicate]

What i want to do is to change the class of the div tag with a toggle button using javascript. So that when i press the button once the div tag gets the show class, and when i press the same button again it gets the hide class. Is this possible?

html:

<a id="togglebutton">Show/hide</a>

<div class="show"> 
   I want this div to toggle between the 'show' class and the 'hide' class
</div>

css:

.show {
    display: block;
}


.hide {
    display: none;
}

js:

function toggle(){
    var hide = document.querySelector(".hide");
    var show = document.querySelector(".show");

}

var hidebutton = document.querySelector(".togglebutton");
hidebutton.onclick = toggle

Would document.getElementById("MyId").className = "MyClass"; be usable somehow?

like image 791
Andrew P Avatar asked Jan 08 '14 17:01

Andrew P


People also ask

Can you have 2 classes in a div?

Absolutely, divs can have more than one class and with some Bootstrap components you'll often need to have multiple classes for them to function as you want them to. Applying multiple classes of course is possible outside of bootstrap as well. All you have to do is separate each class with a space.

How can I use two CSS class in one div?

To specify multiple classes, separate the class names with a space, e.g. <span class="left important">. This allows you to combine several CSS classes for one HTML element.

How do I give a div 2 classes?

To define multiple classes, separate the class names with a space, e.g. <div class="city main">. The element will be styled according to all the classes specified.

How do you toggle between classes in HTML?

Step 1) Add HTML: 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).


1 Answers

You can use

if(document.getElementById("MyId").className == "hide")
   document.getElementById("MyId").className = "show";
else
   document.getElementById("MyId").className = "hide";

But you need first to give an ID to the div.. Please find below a working example: http://jsfiddle.net/HvmmY/

like image 180
Khaled Hamdy Avatar answered Sep 19 '22 16:09

Khaled Hamdy