Why does the address bar show value changes in IE when using window.location.hash, but the value doesn't change in the DOM when going

Here is a sample JavaScript code that attempts to detect the back button event:

document.location.hash="#1";
document.location.hash="#2";
document.location.hash="#3";

function check() {
    if("#3"!=window.location.hash) {
        alert("Back button clicked");
    }
    setTimeout(check, 100);
}
check();

This method works in Firefox and Chrome, but in Internet Explorer (IE), the window.location.hash always remains as "#3" even when clicking the Back button and observing the URL changing to #2 and #1 in the address bar.

Is there any workaround to make IE recognize the hash change when navigating back and forth?

Answer №1

If the hash is being updated dynamically through user interactions or timed events, you can utilize the window.onhashchange event to monitor these changes instead of using setTimeout to check the hash.

window.onhashchange = function(e) {
  alert('Back button clicked');
}

This event will trigger whenever the hash is modified, whether by navigating through history or programmatically changing it. If you only want your code to run when navigating with history buttons, you can incorporate an if statement to control this behavior. Check out this example for reference:

Alternatively, you could structure your code to respond to hash changes and manually updating the hash in a way that ensures your code executes as intended.

Here's an example setup:

<a href='#1' class='nav'>1<a/>
<a href='#2' class='nav'>2<a/>
<a href='#3' class='nav'>3<a/>

And the corresponding JavaScript/jQuery:

/*$('.nav').click(function() {                 // Uncomment this block if not modifying hash in HTML
  window.location.hash = '#' + $(this).html(); 
});*/
function getLocationHash() {
  return window.location.hash.substring(1);
} 

window.onhashchange = function(e) {
  switch(getLocationHash()) {
    case '1': 
      execute code block 1;
      break;
    case '2':
      execute code block 2;
      break;
    case '3':
      execute code block 3;
      break;
    default: 
      // Code to be executed for other cases
  }
}

You can see a similar implementation on my website:

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

Updating parent components through child components in ReactWould you like another unique

In my current project, I am attempting to change the state of the main component labeled App.tsx by using a child component called RemarksView.tsx. I have attempted passing props such as setRemarks and remarks, but unfortunately the state in the parent c ...

Strange behavior detected in TypeScript generic function when using a class as the generic parameter

class Class { } const f0 = <T extends typeof Class> (c:T): T => { return c } const call0 = f0 (Class) //ok const f1 = <T extends typeof Class> (c:T): T => { const a = new c() return a //TS2322: Type 'Class' is not assigna ...

Unable to create a new collection in Firebase Firestore

I encountered an issue while trying to add a collection in Firebase Firestore using the function .collection(doc).set. Despite finding the new user in authentication in Firebase, the collection was not created and the console displayed an error message. ...

Guide on utilizing map function in JavaScript and Vue to generate a fresh array

I am working on implementing a map method in JavaScript and Vue to generate a new array of objects while only including specific items in each object. I have designed a user interface with 2 checkboxes corresponding to 2 distinct objects: <div v-for ...

JavaScript - Dynamically loaded CSS: CSS variables are not immediately accessible to JavaScript, but are successfully evaluated within the CSS itself

I am encountering an issue with dynamically loading stylesheets via JavaScript into my application. Within these stylesheets, I have various CSS variables that I need to access and modify from my JavaScript code. When the stylesheets are directly embedded ...

Easy Ways to Personalize the Appearance of Your Material-UI Tab Indicator

I've been working on customizing the tab indicator in material-ui and so far I've only been able to make rectangular or square shapes. I'm wondering if there's a way to turn it into an arrow or an upside-down triangle instead? Here is ...

Learn how to create a web application by utilizing HTML5 and REST, and then seamlessly transfer the front-end code to a mobile app using Cordova

Can a mobile application be developed from a web portal using Cordova or similar frameworks? The web portal will consist of: HTML5 for front-end J2EE for back-end with JAX-RS Is it feasible to extract pages from the web portal and integrate them into a ...

What is the best way to display items within a table using React?

I'm just starting to learn React. Can someone show me how to use the "map" function to list elements from two different arrays in two columns? state = { dates: ["2000", "2001", "2002"], cases: ["1", "2", "3"] } render() { return ( <thea ...

"Sorting functionality in Amcharts with dynamic movement of the div as the chart scroll bar is used

After exploring the question discussed here, I discovered that using li wasn't the most suitable option for me. Therefore, after further investigation and following the guidance provided in the example here, I successfully managed to create a customiz ...

Show only a cropped section of a resized image within a div

I have a script that calculates the best region of an image to display within a specific div size. This calculation is done in PHP and generates a JSON output like this: {"scale":1.34,"x1":502,"x2":822,"y1":178,"y2":578} The image in question has dimensi ...

Getting a URL to redirect after a successful login via an AJAX request in PHP

I've been trying to figure out how to redirect the URL after a successful login using an Ajax call in PHP. Can someone please review my code and point out any mistakes? Here is the content of the registration.php file located at http://localhost:8080 ...

Unable to redirect using JQuery Ajax post after receiving an ActionResult from an MVC controller

I'm trying to send data from a method to an MVC controller that gives back an action result, and then have my site automatically navigate to the correct view. Here's the code snippet I'm currently working with: function RedirectFunction(ite ...

The route path consists of data that will be retrieved before entering the route

I am facing an issue with my router configuration. I have a dynamic Route that requires the last part of its path to be set after fetching data from a store call in beforeRouteEnter. beforeRouteEnter (to, from, next) { if(to.params.categoryId) { next(vm ...

Remain on the React page following an HTTP POST request to Flask

Is there a way to stay on the React frontend (localhost 3000) after completing a POST request to a Flask backend from a React form, without redirecting in the Flask backend? Relevant code: export const DateForm = () => { return ( <div&g ...

Generate a new span element within a div element programmatically using Vuex

I have integrated an existing web application developed using vue.js. Below is the code snippet: function () { var e = this, t = e.$createElement, n = e._self._c || t; return e.messag ...

Utilizing a combination of HTML, AJAX, and PHP, transfer an HTML input array via AJAX to a PHP webpage

Despite trying numerous similar solutions, none of them have proven effective for my issue. Within a form, users can input an unspecified amount of select options that can be added as needed using AJAX. My goal is to post this array to a PHP page via AJAX ...

PHP not displaying line breaks from JavaScript textarea

I am facing an issue while trying to generate a .txt file on my server upon form submission. Despite including newlines in the comment section, they do not show up in the resulting .txt file. Below is the code snippet I am using: Javascript function sen ...

Displaying the saved MTRC (markdown-to-react-components) content from the database

I currently have data stored in a database that has been produced using the markdown-to-react-components package as MTRC(content).tree What is the best way to render this content? I've experimented with various approaches, such as dangerouslyInsertHT ...

Design my div layout to resemble a tree shape

Take a look at this URL. I have dynamically created divs in a nested structure for a sports tournament. I need help styling the divs to match the tournament structure. This is how I want my structure to look. The code is functioning properly, it's ju ...

Use React to increment a variable by a random value until it reaches a specific threshold

I am currently working on creating a simulated loading bar, similar to the one seen on YouTube videos. My goal is for it to last 1.5 seconds, which is the average time it takes for my page to load. However, I have encountered an issue with the following co ...