How to rearrange divs for single page application

eman

New Member
#1
I'm building a single-page web app. In this one file, I want a specific div to be shown on startup. Perhaps the user will then press a button, and a new div will replace it.

Right now, I'm using js to hide one div and show another in this case. The problem is, the new div appears further down the page (as it is written in the html file after the first div).

How can I, using javascript, simply replace one div with another as the user navigates back and forth between the divs? Is this possible and recommended?
Mã:
/* JS
When #firstButton is pressed, replace div #first with div #second
When #secondButton is pressed, replace the div #second with div #first
*/
Mã:
#second {
  visibility: hidden;
}
Mã:
<div id="first">
  <h1>First Page</h1>
  <button id="firstButton">Go to second page</button>
</div>


<div id="second">
  <h1>Second Page</h1>
  <button id="secondButton">Go to first page</button>
</div>
 

Admin

Administrator
Thành viên BQT
#2
Using visibility: hidden is causing your elements to still take up space, which is why your "pages" don't appear to change places.

Switch to display: none, which can be easily toggled with jQuery's .show() and .hide() like so:

Mã:
$("#firstButton").on("click", function() {
  $("#first").hide();
  $("#second").show();
});

$("#secondButton").on("click", function() {
  $("#first").show();
  $("#second").hide();
});
Mã:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="first">
  <h1>First Page</h1>
  <button id="firstButton">Go to second page</button>
</div>

<div id="second" style="display: none;">
  <h1>Second Page</h1>
  <button id="secondButton">Go to first page</button>
</div>
 
Top