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

1

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

You can do this without having to call the function when the user clicks the "next page" button or something.

Comment : When he clicks the "next page" button or something, the page will not reload, just change the url, ie, it's no use simply creating a self-invoked function somewhere in the code

    
asked by anonymous 15.06.2018 / 22:36

1 answer

1

Example of using 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>
    
16.06.2018 / 01:21