JS will reach its stopping point at the specified style.zIndex

I am currently in the process of setting up button elements. I have two scripts that correspond to different types of buttons - one script runs a simple collapse menu, while the other executes a more complex collapse by shifting depths and sliding one div over another. Everything seems to be functioning correctly except for the depth (zindex) switch. Whenever I implement the depth switch, it stops running anything beyond that point. Below is the specific script causing issues.

/* fetching all menu and page buttons */
var menuButtons = document.getElementsByClassName("menuButton");
var pageButtons = document.getElementsByClassName("pageButton");
/* initializing working array index */
var i;
/* IDs of previous and current content pages */
var prevPage;
var currentPage;
/* when a page button is clicked, set the prevPage to the lowest depth and slide the new page overtop */
for (i = 0; i < pageButtons.length; i++) {
  pageButtons[i].addEventListener("click", function() {
    this.classList.toggle("active");
    /* fetching reference to target page from the button */
    var pageId = this.getAttribute("pageTarget");
    currentPage = document.getElementById(pageId);
    /* setting content page depths */
    prevPage.style.zIndex = "0";
    currentPage.style.zIndex = "1";
    /* setting the left position to start the page transition */
    currentPage.style.left = "100vw";
    alert("button clicked");
    /* triggering a delayed function to clear the previous page */
    clearPrevPage();
  });
};
/* delayed function that transitions prevPage to its starting position */
function clearPrevPage() {
  setTimeout(function() {
    prevPage.style.left = "100vw";
    /* setting the variable for the next run */
    prevPage = currentPage;
    alert("delayed");
  }, 400);
};

Answer №1

Before using prevPage, make sure it is not empty to avoid any errors:

/* accessing menu and page buttons */
var menuButtons = document.getElementsByClassName("menuButton");
var pageButtons = document.getElementsByClassName("pageButton");
/* defining index in array*/
var i;
/* id of previous and current content pages */
var prevPage;
var currentPage;
/* when a page button is clicked, set prevPage to lowest depth and animate new page over it */
for (i = 0; i < pageButtons.length; i++) {
  pageButtons[i].addEventListener("click", function() {
    this.classList.toggle("active");
    /* getting the target page of the button */
    var pageId = this.getAttribute("pageTarget");
    currentPage = document.getElementById(pageId);
    /* setting depths for content pages */
    if (prevPage) prevPage.style.zIndex = "0";
    currentPage.style.zIndex = "1";
    /* starting page transition by setting left position */
    currentPage.style.left = "100vw";
    alert("button clicked");
    /* calling delayed function to clear previous page */
    clearPrevPage();
  });
};
/* function to transition prevPage back to starting position after delay */
function clearPrevPage() {
  setTimeout(function() {
    if (prevPage) prevPage.style.left = "100vw";
    /* updating prevPage for next run */
    prevPage = currentPage;
    alert("delayed");
  }, 400);
};
<button class="menuButton">menu</button>
<button class="pageButton" pageTarget="page1">page</button>
<div id="page1">page1</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to position the section and footer to the left side of the sidenav?

I am relatively new to the world of html and css, trying my hand at constructing html layouts. I have encountered a bit of trouble in aligning the footer and section to the left of the nav bar. No matter what percentage widths I use, they always end up ove ...

Displaying JavaScript values one by one using a for loop and alert

Having an issue with looping through a JSON array in JavaScript. I am trying to extract only SG_J1001 and SG_LS01, but it's not working as expected. The result is coming out like this [{"regis ....... var item = JSON.stringify(data['code'] ...

Display issue with loading animation

After clicking the button and seeing the alert message, I noticed that the loading animation does not display during the await new Promise(r => setTimeout(r, 2000));. /* script.js */ async function refreshStatus() { document.getElementById("load ...

Using an external script to modify or call a Vue.js method

My Vue app is constructed using Webpack and includes a few basic computed properties, such as calculating the sum amount from input values. However, I now require the capability to replace the summation function with one stored in a separate file that is n ...

The latest version of Next.js, Version 12, encounters an issue with theme-ui that results in the error message "code: 'ERR_REQUIRE_ESM'"

Encountering an error while working with Next.js 12 after creating a theme using theme-ui. https://i.stack.imgur.com/BtH7W.png Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: E:\fm-nextjs\node_modules\@mdx-js\react\ind ...

Error: Missing provider for MatBottomSheetRef

While experimenting in this StackBlitz, I encountered the following error message (even though the MatBottomSheetModule is imported): ERROR Error: StaticInjectorError(AppModule)[CountryCodeSelectComponent -> MatBottomSheetRef]: S ...

Why is there a node_modules folder present in the npm package I authored when using it as a dependency in another module?

After successfully launching my first npm package, I noticed something strange when installing it as a dependency in my project. Upon exploring the project folder in node_modules, I discovered an unexpected node_modules folder containing just one package ...

What is causing the body to be partially hidden on the right side of every mobile device screen?

I'm currently addressing the mobile optimization issues on a website that I've been developing for some time, and I've encountered my first obstacle. When viewing it on an iPad, the body of the site doesn't extend all the way to the rig ...

Determine the number of input tags within a div element by utilizing the closest property in jQuery

Sorry for the silly question, but I've been struggling to find a solution. Spent hours scratching my head. Here is my HTML structure: <div class= 'container'> <div class="someclass"> <input>some content</in ...

When using CSS border-width:1px, I notice that the borders aren't consistently thin

I'm attempting to add thin borders to a div. My CSS code is as follows: border: solid; border-width: 1px; However, the resulting borders appear unevenly thin in my browser. The borders on the left and bottom seem thicker than those on the right and ...

Menu button is expanded without the need to click

The Bootstrap 5 button extends the default behavior and does not collapse. Here is the code: <nav id="header-nav" class="navbar navbar-expand-lg navbar-light"> <div class="container"> <a class= ...

Learn how to properly convert a string into a valid URL using the Next JS router when pushing pages

I'm dealing with a string that looks like this: /dashboard/products/:id. My goal is to utilize Next Js's router to navigate to that URL and replace the placeholder :id with an actual id. Here's the code I've written: {products.map(prod ...

Using JavaScript to eliminate brackets

When a map is clicked, I have a function that retrieves GPS coordinates. However, the result is currently displayed in brackets (). It is necessary to eliminate the brackets. function onClickCallback(event){ var str = event.latLng var Gpps = str / ...

bespoke design picture holder

Is it possible to create a custom-shaped image container without using <div />? I encounter an issue when trying to add corners on top of the #content-box as shown in this screenshot: . The corner images only cover half of the block element, with th ...

Issue with JQuery loading causing disruption to HTML text formatting

I set up a heading on my website by using the following HTML code: <div id="question"> <h1>Question Goes Here</h1> </div> The font style is controlled by my CSS and it's set to size h1. The text displayed there is tempora ...

Having trouble updating text in a PDF using NodeJS and hummus library

How can NodeJS be used to replace a string in a PDF file? offers a solution for text replacement in a PDF document. However, when applying the same code, an issue arises where the replaced text is visible in the source code of the PDF but does not render p ...

How should one correctly trigger an event in Google scripts?

When it comes to calling in the active elements, I have been using event.source.getActive and SpreadsheetApp.getActive. However, I have noticed that I sometimes interchange them in my script and face issues. So, I am unsure about which method is more app ...

Can you explain the purpose of prevState within the setState method of a functional component?

When returning the updated previous state within a setState method retrieved from the useState hook, it appears that the state remains unchanged. To demonstrate this behavior, consider running the following code snippet: function App(){ const [state, ...

React fails to trigger a re-render despite updating the state following an API call

Recently, I started working with React and attempted to retrieve data from my API. However, changing the state does not trigger a re-render of the component. Inside the useEffect function in my component, I have code that fetches the API and then sets the ...

What is the best way to calculate the number of items in your mongoose reference with a specific field?

I am trying to calculate the number of active Workers that belong to a specific company. Here is an example scenario: const workerSchema = new Schema( { userId: { type: Types.ObjectId, ref: 'User', ...