javascript - How to make next and back buttons with div array? - Stack Overflow

admin2025-04-16  3

I'm coding a website and for the life of me i cannot find a way to get a functioning

way to get all four buttons to work.

var divs = ["Page1", "Page2", "Page3"];
var visibleDivId = null;
var i, divID, div;

function divVisibility(divID) {
  if (visibleDivId == divID) {
    visibleDivId = null;
  } else {
    visibleDivId = divID;
  }
  hideNonVisibleDivId();
}

function hideNonVisibleDivId() {
  for (i = 0; i < divs.length; i++) {
    divID = divs[i];
    div = document.getElementById(divID);
    if (visibleDivId === divID) {
      div.style.display = "block";
    } else {
      div.style.display = "none";
    }
  }
}

}
<HTML>

<Head>

</Head>

<Body>
  <Center>

    <table style="border-radius:15px 15px 15px 15px;">

      <tr>
        <td>
          <center>
            <div style="width:850px; border:3px black solid; margin-top:30px; margin-bottom:-10px; border-radius:8px 8px 8px 8px; background-image: url('.png')">

              <!-- toolbar -->
              <table style="border-top: none; height:0px;">

                <tr>
                  <td>
                    <center>
                      <div class="toolbar" style="border-radius:15px 15px 15px 15px;">

                        <font size="3"><b>~&nbsp;&nbsp;/ 
<a href="#" onClick="divVisibility('Page1')">&nbsp;&nbsp;&nbsp;First&nbsp;&nbsp;&nbsp;</a> /
<a>&nbsp;&nbsp;&nbsp;Back&nbsp;&nbsp;&nbsp;</a> /
<a>&nbsp;&nbsp;&nbsp;Next&nbsp;&nbsp;&nbsp;</a> /
<a href="#" onClick="divVisibility('Page3');">&nbsp;&nbsp;&nbsp;Latest&nbsp;&nbsp;&nbsp;</a> / &nbsp;&nbsp;~</b></font>

                      </div>
                    </center>
                  </td>
                </tr>

              </table>
              <!-- diary -->

              <table style="border-radius:15px 15px 15px 15px;">

                <tr>
                  <td>
                    <center>
                      <div id="diary">

                        <div id="Page1">

                          egg

                        </div>

                        <div id="Page2" style="display: none;">

                          egg bacon

                        </div>

                        <div id="Page3" style="display: none;">

                          egg bacon cheese

                        </div>

                      </div>
                    </center>
                  </td>
                </tr>
              </table>
            </div>
          </center>
        </td>
      </tr>
    </table>
  </center>
</body>

</html>

I'm coding a website and for the life of me i cannot find a way to get a functioning

way to get all four buttons to work.

var divs = ["Page1", "Page2", "Page3"];
var visibleDivId = null;
var i, divID, div;

function divVisibility(divID) {
  if (visibleDivId == divID) {
    visibleDivId = null;
  } else {
    visibleDivId = divID;
  }
  hideNonVisibleDivId();
}

function hideNonVisibleDivId() {
  for (i = 0; i < divs.length; i++) {
    divID = divs[i];
    div = document.getElementById(divID);
    if (visibleDivId === divID) {
      div.style.display = "block";
    } else {
      div.style.display = "none";
    }
  }
}

}
<HTML>

<Head>

</Head>

<Body>
  <Center>

    <table style="border-radius:15px 15px 15px 15px;">

      <tr>
        <td>
          <center>
            <div style="width:850px; border:3px black solid; margin-top:30px; margin-bottom:-10px; border-radius:8px 8px 8px 8px; background-image: url('https://basilthesheep.neocities.org/SiteImages/color2.png')">

              <!-- toolbar -->
              <table style="border-top: none; height:0px;">

                <tr>
                  <td>
                    <center>
                      <div class="toolbar" style="border-radius:15px 15px 15px 15px;">

                        <font size="3"><b>~&nbsp;&nbsp;/ 
<a href="#" onClick="divVisibility('Page1')">&nbsp;&nbsp;&nbsp;First&nbsp;&nbsp;&nbsp;</a> /
<a>&nbsp;&nbsp;&nbsp;Back&nbsp;&nbsp;&nbsp;</a> /
<a>&nbsp;&nbsp;&nbsp;Next&nbsp;&nbsp;&nbsp;</a> /
<a href="#" onClick="divVisibility('Page3');">&nbsp;&nbsp;&nbsp;Latest&nbsp;&nbsp;&nbsp;</a> / &nbsp;&nbsp;~</b></font>

                      </div>
                    </center>
                  </td>
                </tr>

              </table>
              <!-- diary -->

              <table style="border-radius:15px 15px 15px 15px;">

                <tr>
                  <td>
                    <center>
                      <div id="diary">

                        <div id="Page1">

                          egg

                        </div>

                        <div id="Page2" style="display: none;">

                          egg bacon

                        </div>

                        <div id="Page3" style="display: none;">

                          egg bacon cheese

                        </div>

                      </div>
                    </center>
                  </td>
                </tr>
              </table>
            </div>
          </center>
        </td>
      </tr>
    </table>
  </center>
</body>

</html>

I've tried to make it so: First always goes to the first div (page1) Next will go to page 2 3 4 etc. Back will go back to page 3 2 1 etc. and Latest will go to the last div (currently page3)

only First and Latest will work

Edit: To clarify I'm horribly new to JavaScript, The functions on the back and next button were just placeholders. The Answers I got were good but I don't want to add buttons. Thank you for your help so far though!

Share Improve this question edited Feb 5 at 16:34 Millani Jones.C asked Feb 2 at 2:25 Millani Jones.CMillani Jones.C 11 silver badge1 bronze badge 12
  • Where are the backward() and forward() functions? – Barmar Commented Feb 2 at 2:47
  • You have an extra } at the end of the JavaScript. – Barmar Commented Feb 2 at 2:47
  • 3 @SergeyAKryukov You can do it that way, but using a class is more flexible, since you can just change the CSS to change how the current item is displayed. – Barmar Commented Feb 2 at 3:41
  • 1 @SergeyAKryukov Semantic markup is also generally considered "better". Manipulating styles directly in code is usually considered a poor approach. – Barmar Commented Feb 2 at 3:46
  • 1 <center> tag is loooong time deprecated. Use CSS instead. – Roko C. Buljan Commented Feb 2 at 12:25
 |  Show 7 more comments

3 Answers 3

Reset to default 0

Here is a version that shows that eventListeners are useful

window.addEventListener('load', () => {
  const nav = document.querySelector('nav');
  const buttons = nav.querySelectorAll('button')
  const pages = document.querySelectorAll("body > section");
  const lastPage = pages.length - 1;
  buttons[0].disabled = true; // can be done in html too
  buttons[1].disabled = true;
  let cnt = 0;
  nav.addEventListener('click', (e) => {
    const tgt = e.target.closest('button');
    if (!tgt) return; // not a button
    const id = tgt.id;
    switch (id) {
      case 'first': cnt = 0; break;
      case 'prev':  cnt = Math.max(cnt - 1, 0); break;
      case 'next':  cnt = Math.min(cnt + 1, lastPage); break;
      case 'last':  cnt = lastPage; break;
    }
    pages.forEach((page, i) => page.classList.toggle('active', i === cnt));
    buttons.forEach((button, i) => button.disabled = i < 2 ? cnt == 0 : cnt >= lastPage);
  });
});
* {
  font-family: sans-serif;
}

body>section {
  display: none;
}


button {
  font-size: 160%;
}

body>section.active {
  display: block;
}
<nav><button id="first">⇤</button><button id="prev">←</button>
  <button id="next">→</button><button id="last">⇥</button>
</nav>

<section class="active">Page 1</section>
<section>Page 2</section>
<section>Page 3</section>
<section>Page 4</section>

How It Works:

HTML Structure:
We have a container with multiple divs (content). Initially, we set only the first div to be visible (style="display:block;"), and others are hidden (style="display:none;"). There are two buttons: Next and Back.

CSS:
The .content divs are set to be hidden initially. This will be controlled via JavaScript by changing their display property to block (for visible) or none (for hidden).

JavaScript Logic:
We select all the .content divs using querySelectorAll and store them in an array-like object divs. We maintain a variable currentIndex to track which div is currently visible. The showNextDiv() function increments currentIndex, hides the current div, and shows the next one. Similarly, the showPrevDiv() function decrements currentIndex, hides the current div, and shows the previous one. Event listeners on the Next and Back buttons call these functions when clicked.

Look how simple it can be:

"use strict";

window.onload = () => {

    const pages = document.querySelectorAll("body > section");
    const back = document.querySelector(
        "body button:first-child");
    const forward = document.querySelector(
        "body button:last-of-type");
    let current = 0;

    const updateEnabled = () => {
        back.disabled = current < 1;
        forward.disabled = current >= pages.length - 1;
    }; //updateEnabled
    updateEnabled();

    const move = backward => {
        pages[current].style.display = "none";
        if (backward) current--; else current++;
        pages[current].style.display = "block";
        updateEnabled();
    } //move

    back.onclick = () => move(true);
    forward.onclick = () => move(false);

};
            * { font-family: sans-serif; }
            body > section { display: none; }
            body > section:first-of-type { display: block; }
            button { font-size: 160%; }
<!DOCTYPE html>
<html>
    <body>
        <head><button>⇦</button><button>⇨</button></head>
        <section>Page 1</section>
        <section>Page 2</section>
        <section>Page 3</section>
        <section>Page 4</section>
    </body>
</html>

Pay attention to these moments:

  • Don't repeat document.getElementById, better do it once for all elements, but...
  • Use document.querySelectorAll instead to avoid using id attributes and take an entire group of elements at once.
  • Note that you get a group of pages as an array. This way, you don't need to define the first and last indices, you know it from the array.
  • Also, the array of sections gives us a big benefit: you can add or remove sections in HTML without any modifications in the code.
  • Note the use of const and let. Almost everything is const.
  • You don't need any loops.
  • The property .disabled on buttons saves you from redundant checks.
  • Selectors become simpler if you avoid div and use semantic elements. It also makes the code more readable.
  • "use strict"; don't use sloppy.
转载请注明原文地址:http://anycun.com/QandA/1744811281a87949.html