The back button on the page does not reset the CSS styling

I have a button that activates navigation to a different page.

When this button is clicked, it changes the current section/page's display settings to none and sets the new section/page's display to block.

<div class="listLeft"><p class="listItems" onclick="navButtons('work')">work</p><p class="listItems" onclick="navButtons('about')">about</p></div>
<div class="listRight"><p class="listItems" onclick="navButtons('playground')">playground</p><p class="listItems" onclick="navButtons('contact')">contact</p></div>

JavaScript function below:

function navButtons(page) {
  let section = document.getElementById(page);
  section.setAttribute("class", "visible");
  
  window.location.href = `#${page}page`;
  window.scrollTo(0, document.body.scrollHeight);
  let pagesArrayCopy = [...pagesArray]
  const unselected = pagesArrayCopy.filter(item => item.id !== page);
  setTimeout(() => {
      unselected.forEach((el, index) => unselected[index].setAttribute("class", "invisible"));
      pagesArray = Array.from(pagesNodeList);
    }, 500);
};

After pressing the back button, the URL reverts to the old #section, but the CSS properties remain unchanged, leaving the new page still visible and the previous page with display set to none.

How can I ensure that when the back button is pressed, the CSS values reset to their default state?

Answer №1

Consider utilizing an anchor tag to ensure your URL updates (e.g., change the address to mypage.html#page2). Afterwards, you can attach a function to onhashchange and verify if your page is correctly displayed.

Answer №2

It seems like some of the HTML code is missing as there is no ID provided, resulting in a null section.

function navigateToSection(page) {
  let section = document.getElementById(page);
  console.log(section)
  section.setAttribute("class", "visible");
  
  window.location.href = `#${page}page`;
  window.scrollTo(0, document.body.scrollHeight);
  let pagesArrayCopy = [...pagesArray]
  const unselected = pagesArrayCopy.filter(item => item.id !== page);
  setTimeout(() => {
      unselected.forEach((el, index) => unselected[index].setAttribute("class", "invisible"));
      pagesArray = Array.from(pagesNodeList);
    }, 500);
};
<div class="listLeft">
   <p class="listItems" onclick="navigateToSection('work')">work</p>
   <p class="listItems" onclick="navigateToSection('about')">about</p></div>
   
<div class="listRight">
<p class="listItems" onclick="navigateToSection('playground')">playground</p>
<p class="listItems" onclick="navigateToSection('contact')">contact</p></div>

Answer №3

To make your changing state sync with the browser's history, one approach is to bind it to the history of the browser itself. Since overriding the 'back' button functionality is not feasible, integrating this feature into your browsing history is a suitable alternative. Explore the History API for HTML5 by visiting: https://css-tricks.com/using-the-html5-history-api/

Alternatively, you can achieve the same outcome using this plugin: https://code.google.com/archive/p/reallysimplehistory/

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

Filter an array of dates that fall within a specified range of two dates

I have a list of dates and I'm attempting to filter out dates that fall outside of a specific date range. However, I'm encountering an issue where some dates before the "from" date are still present in the filtered list. What could be causing thi ...

Switch from HTML symbol to Java symbol

Is it possible to change an HTML symbol into a Java symbol? For instance, if I have &#xe000, is there a way to obtain the Java char representation like \ue000? What steps should I take to achieve this conversion? ...

Using the Rails framework, a basic "remote: true" request does not produce a JavaScript response

In my Rails app, I have set up an iframe to display static HTML files from the same domain. Inside the iframe, I added a link with the remote attribute in hopes of making an in-place AJAX call to create a new nested resource. Here is the code snippet: --- ...

Creating a structured HTML/PHP page for permanent redirection to another webpage

I'm trying to restructure a part of my website, but I'm struggling to figure out how to do it. This is in the context of a logged-in user: On page 1, the user clicks a button to navigate to page 2 On page 2, the user performs an OPERATION to go ...

What is the best method for accessing the service response data when I am sending back an array of custom map with a promise as an object?

Sharing my code snippet below: function createObject(title, array){ this.title = title; this.array = array; } //$scope.objects is an array of objects function mapPromise(title, promise){ this.title= title; this.promise = promise; }; var fet ...

Divs are stubbornly resisting the urge to behave like block elements

.useless { float: right; clear: right; border: 1px dashed blue; height: 50px; width: 100%; } div.pretraga { border: 3px groove red; width: 20%; float: right; margin-right: 5%; border-top: 0; display: flex; justify-content: center; height: 250px; <div cl ...

Tips for resizing images to have uniform dimensions

I am trying to create an image gallery where all the images are uniform in size. Currently, I am referencing this tutorial for guidance on my CSS. div.gallery { border: 1px solid #ccc; } div.gallery:hover { border: 1px solid #777; } div.gallery img ...

Troubleshooting UDP output issues in FFMPEG

Currently attempting to stream a video via ffmpeg to a udp stream by piping rawvideo directly into ffmpeg using ffmpeg.stdin.write(data). Here are my specified options/parameters: var ffmpegArgs = [ '-c:v', 'rawvideo',// input cont ...

Error in jQuery validation caused by a different value

I have a form on my website that needs to run some validations. One specific validation requires a file to be uploaded in order for a group of checkboxes to be selected. The issue I am facing is that the validations only seem to work when triggered, and b ...

Using jQuery to modify z-index on hover

Is there a way to dynamically adjust the z-index of an img element when hovered over? I want the z-index to be 0 when the mouse pointer is outside of the image, and 9 when hovering over it. I know how to initially set the z-index, but need help with chang ...

Creating a circular price display using CSS:

Below is the code snippet that I am working with: .special-price { text-align: center; background-color: #2e566e; } .special-price .offer { border-radius: 50%; background-color: #56c243; color: #fff; font-weight: 700; font-size: 18px; h ...

Displaying values in form fields when a specific class is present

Whenever I input and submit the form fields correctly using #submit_btn, my values disappear. However, when they are not valid, this issue does not occur. I attempted to address this problem with jQuery: $('#submit_btn').click(function() { i ...

Having trouble with adding the copy to clipboard feature

I'm having trouble implementing a copy to clipboard option on my color selector. The goal is to display the selected color on an h3 tag and create a background color generator. Each time a color is chosen, it should appear on screen for us to easily c ...

JavaScript parameter not found

I am currently working on a block type plugin for Moodle and encountering some difficulties with my JS code. Due to my limited knowledge in JS and JSON, I am having trouble identifying the issue at hand. My code includes a function that adds a custom actio ...

JavaScript is a powerful tool for reading JSON files

I'm trying to figure out how to parse a nested object in JSON using JavaScript. Here's the code I have so far: var myRequest = new Request('test.json'); fetch(myRequest) .then(function(response) { return response.json(); }) .then( ...

How can I implement a Dynamic Input field using Angular?

Suppose there is an input field where a user enters an ID. Once the user clicks the "add" button, I need to send a request to my server to fetch a "name". Afterwards, I want to disable the text input field, hide the "add" button, and show a number input fi ...

Guidelines on creating actionable functions using JavaScript

Having trouble connecting the form to the database and looking for a solution. This is the HTML form that I've been working on, attempting both POST and GET methods. <form id="register" action="script/register.js" method="post"> <label for= ...

Changing the visibility of a div with an onClick event in React

Can anyone help me figure out how to toggle the display of this div on click? I've been struggling with it for a while now. Any suggestions are welcome. https://i.sstatic.net/lPZtN.png https://i.sstatic.net/8Pybg.png ...

JavaScript: Share module contents internally through exporting

When working with Java, there are 4 different visibility levels to consider. In addition to the commonly known public and private levels, there is also the protected level and what is referred to as the "default" or "package-local" level. Modifier Clas ...

What is the best way to eliminate the white margin that is showing up on the right side of my website?

Here's a question that has been bugging me recently... So, I've been working on creating my own version of an Airbnb website called 'tombnb' for a few weeks now. Everything was going smoothly until I encountered a persistent issue. Th ...