I have 2 divs which and I want to be able to toggle between them onClick of a button (currently using .toggle();)
The div that shows on the page is div1. This div has th
Here is a simple way to do it:
For the html, we have a simple button to call the "toggleFunction" that will add and remove display classes to our Div elements as necessary.
<button onclick="toggleFunction()" >Click to toggle</button>
<div id="div1" class=" " > Now showing "Div 1" </div>
<div id="div2" class=" " > Now showing "Div 2" </div>
We'll set the default display properties of Div 1 and Div 2 to "inline" and "none" respectively, so that by default:
Here is the css for that:
#div1 {
display: inline;
color:blue;
}
#div2 {
display: none;
color:red;
}
.display-none {
display: none !important;
}
.display-inline {
display: inline !important;
}
Here is the Jquery for that:
function toggleFunction() {
$("#div1").toggleClass("display-none");
$("#div2").toggleClass("display-inline");
}
You can try it out on codepen here: http://codepen.io/anon/pen/vEbXwG
I would use .toggleClass() as toggle switches between display: inline;
and display: block;
Create a hidden and inline class and just toggle those.
Using plain JavaScript, you could use:
document.getElementById('div1').style.display = 'none';
document.getElementById('div2').style.display = 'inline';