How do you trigger an event when the URL changes without the page reloading in javascript?

1.1k Views Asked by At

For example, if I click the 'next' button on a webpage, the website displays the results of the next page but does not reload the page, whilst the URL changes. How would I detect this change in URL and trigger an event accordingly on the newly displayed page?

1

There are 1 best solutions below

0
Paweł Reliński On

After click 'next' button you would do action which get new URL address and do action based on the new data.

For example:


nextBtn.addEventListener('click', () => {
  const currentLocation = window.location;
  // here you can get data from URL and do whatever you want with it
});

But you can also use library like rxjs to subscribe url from others files.

For example:

file1.js

nextBtn.addEventListener('click', () => {
  const currentLocation = window.location;
  publisher.next(currentLocation);
});

file2.js
publisher.subscribe(location => {
  // and you have your url data in another file
});