skip to Main Content

I’m trying to make a site that will switch between scanned images of the pages of my sketchbook using 2 different buttons on either side of the image. All of the URLs of the images are the same except for the page number in the URL. I have been attempting to use Javascript to make the buttons change the number in the URL to change the image.

I succeeded in making Javascript provide the number in the URL for the image, however, no matter WHAT I’ve tried, the buttons refuse to actually change the number. Even though it feels like something so simple should be easy.

I’ve tried various if/else statements. I’ve tried a while/do statement. I’ve tried "pageNumber++" and "pageNumber+=1". I learned the basics of JQuery to see if it would help in any way only to realize that the problem that it solves is not the problem I’m having. And frankly, I’m starting to feel pretty upset.

This is the basics of my setup minus any button functions:

<div> <--! This div is also a flexbox btw -->
    <button><h3>Previous</h3></button> <--! There's nothing happening with this button because I was just trying to figure out the other one first -->
 
    <a href="" id="pagelink" target="_blank"><img src="" height="400px" id="page-holder"></a>
          
    <button id="nextbutton"><h3>Next</h3></button>
</div>

<script>
let pageNumber = 1;
        
let currentPage = "https://example.com/Images/Art/Sketchbook Page " + pageNumber + ".png";
        
const pageHolder = document.getElementById('page-holder');
const pageLink = document.getElementById('pagelink');
const nextButton = document.getElementById('nextbutton');
        
pageHolder.src = currentPage;
pageLink.href = currentPage;

//Input all of the different button functions I tried here          

</script>

If anyone has any idea of how I can successfully do this, that would be greatly appreciated.

Btw, I’m also using http://www.w3schools.com/lib/w3data.js to help with having the same html pieces on multiple sites without having to go and update them all individually, which I don’t think would be interfering with this, but I don’t even know anymore 🙁

2

Answers


  1. You have to specify "what to happen" when clicking a specific element. Since You haven’t done that all the JS code you have written here will be executed as soon as the page is loaded. In this case, You have to add an EventListener to your Previous and Next buttons, and you have to write your logic inside of the callback function.

    <div>
        <button id="prevbutton"><h3>Previous</h3></button>
     
        <a href="" id="pagelink" target="_blank">
          <img src="" height="400px" id="page-holder">
        </a>
              
        <button id="nextbutton"><h3>Next</h3></button>
    </div>
    
    <script>
    
    let pageNumber = 1;
    let imageBaseUrl = "https://example.com/Images/Art/Sketchbook Page ";   
    
            
    const pageHolder = document.getElementById('page-holder');
    const pageLink = document.getElementById('pagelink');
    const previousButton = document.getElementById('prevbutton');
    const nextButton = document.getElementById('nextbutton');
    
    previousButton.addEventListener("click", function(){
    
      if ( pageNumber === 0 ) {
         // You may not need the pageNumber in negative numbers
         return;
      }
    
      pageNumber--;
      let imageUrl = imageBaseUrl + pageNumber + ".png";
      pageHolder.src = imageUrl;
      pageLink.href = imageUrl;
    });
    
    nextButton.addEventListener("click", function(){
      pageNumber++;
      let imageUrl = imageBaseUrl + pageNumber + ".png";
      pageHolder.src = imageUrl;
      pageLink.href = imageUrl;
    });         
    
    </script>
    
    Login or Signup to reply.
  2. You can implement cycling forward and backward through a list of image URLs by storing the URLs in an array and keeping track of the current image URL index. When you want to update the image source to the next image, modify the index to the next valid array index and then change the source. To go backward, subtract from the index instead.

    Below is a reproducible example that you can use. It includes comments at each step to help explain. Additionally, here are some links to documentation for some of the APIs that are used:

    "use strict";
    
    // Create an array of the image URLs.
    // I found these examples in a random npm package called "dog-cat-photo":
    const imageUrls = [
      "cat.png",
      "cat_1600771384399.png",
      "dog.png",
      "dog_1600771291892.png",
      "dog_1600771306027.png",
    ].map((fileName) =>
      `https://cdn.jsdelivr.net/npm/[email protected]/${fileName}`
    );
    
    // Store the index of the current image URL.
    // It is initialized to the last valid index in the array
    // so that the initial update (below) will display the first image:
    let currentImageIndex = imageUrls.length - 1;
    
    // Create a reference to the image element:
    const img = document.querySelector("img.current");
    
    // Update the index by incrementing or decrementing it,
    // ensuring that it stays in the valid range of array element indexes:
    const changeImage = (prevOrNext) => {
      currentImageIndex = (currentImageIndex + (prevOrNext === "next" ? 1 : -1)) %
        imageUrls.length;
      if (currentImageIndex < 0) currentImageIndex += imageUrls.length;
      img.src = imageUrls[currentImageIndex];
    };
    
    // Initialize the image source to the first URL in the array:
    changeImage("next");
    
    // Bind a click event listener to the "previous" and "next" buttons,
    // which invokes the function above, effectively updating the image source:
    document.querySelector("button.img-control.previous")
      .addEventListener("click", () => changeImage("previous"));
    
    document.querySelector("button.img-control.next")
      .addEventListener("click", () => changeImage("next"));
    body {
      font-family: sans-serif;
      background-color: rgb(14, 14, 14);
      color: #fff;
    }
    
    #root {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    
    .img-controls {
      display: flex;
      gap: 1rem;
    }
    
    .img-control {
      font-size: 1rem;
      padding: 0.5rem;
    }
    <div id="root">
      <div class="img-controls">
        <button class="img-control previous">Previous</button>
        <button class="img-control next">Next</button>
      </div>
      <div>
        <img class="current" src="" />
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search