JS / jQuery (hide div, show div on click)

I have two buttons.

I have two divs that I want to show.

Each divs has different content.

I want both divs to take up the same amount of space on the page.

I want this to be loaded on the page, div1 is displayed, and if they click on the link div2, div1 disappears and div2 appears in its place.

What is the best way to do this? And How?

+4
source share
7 answers

All the source CSS and downloads are aloof and you are using jquery, I think you are looking for something like

$("#button2").click(function(){ $("#div1").hide(); $("#div2").show(); }) 
+10
source

Page loading:

 $('#div2').hide(); 

click link:

 $('#div1').hide(); $('#div2').show(); 
+1
source

see sample code here ... hope this helps :)

http://jsfiddle.net/jpHzk/2/

Note: Hi Kyle, I changed my code, added some lines to it, kindly provided by jessegavin

+1
source

In the click handler, call $('#div1').hide() and $('#div2').show() .

0
source
 function showdiv(id){ $("#container div").hide(0); //Hide all DIV within container $("#container #" + id).show(); //Show DIV with certain ID } 

Then in HTML ...

 <a href="javascript:;" onclick="javascript:showdiv('about');">About Us</a> <a href="javascript:;" onclick="javascript:showdiv('contact');">Contact</a> 

You should add event listeners, but I think you did it something like this.

0
source

The way I do this is to give everyone a unique identifier (div1 and div2 will be enough). The deb you want to hide must have inside the style = "display: none" tag. Then, in the div tag you want to click to show the hidden parts, use this code type: onClick = "document.getElementById ('div1') .style.display = 'block'; document.getElementById ('div2'). Style .display = 'none'; " Just change div1 and div2 to another for the opposite effect.

It was assumed that div1 was hidden and div2 was visible at the beginning.

0
source

See the working version on jsFiddle: http://jsfiddle.net/7jWVt/

HTML

 <button id="button1">One</button> <button id="button2">Two</button> <div id="div1"> Here is line one<br/> Here is line two<br/> Here is line three<br/> Here is line four </div> <div id="div2"> Here is line one<br/> Here is line two </div> <p> Here some other paragraph to show that the divs will take up the same amount of space</p> 

JQuery

 $(function() { // Make the divs have equal heights var h1 = $("#div1").height(); var h2 = $("#div2").height(); $("#div1,#div2").height(Math.max(h1,h2)); // Then hide the second div $("#div2").hide(); // Then add a click handlers to the buttons $("#button1").click(function() { $("#div1").show(); $("#div2").hide(); }); $("#button2").click(function() { $("#div1").hide(); $("#div2").show(); }); }) 
0
source

Source: https://habr.com/ru/post/1345486/


All Articles