Is it possible to add an event listener to the url?

Asked

Viewed 77 times

1

The idea is that when there is a change in the url, run a function that will do something with that url, for example, the user is on the page exemplo.com/#/algumacoisa/2 which is a table with pagination, in which case it would be on page 2, and when the url changes to exemplo.com/#/algumacoisa/4, update the table with page 4 data, similar to what the angular does.

It is possible to do this without having to call the function when the user clicks on the "next page" button or something like that.

Observing: when he clicks on the "next page" button or something, the page will not reload, just change the url, that is, it is no use simply creating a function autoinvocated somewhere in the code

  • @dvd thought to do so by adding event listeners at all links, but still give a hand, and if I upload other htmls via ajax would have to add the events again

  • 2

    If what you want is to monitor changes after the hash (#), can use the event hashchange.

  • I could answer with an example?

1 answer

1


Example of use of the event hashchange:

var out = document.getElementById('output');
window.addEventListener('hashchange', function(e) {
    out.innerHTML = 'hash atual: ' + window.location.hash;
});
div {
  border: 1px solid #ccc;
  margin: 10px 0;
  min-height: 16px;
}
<a href="#div1">Link 1</a><br>
<a href="#div2">Link 2</a><br>
<a href="#div3">Link 3</a><br>

<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>

<div id="output"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.