0

I am using the following code to change the display of elements. I use jQuery and my problem is that it only checks URL in the begging and in the next change of URL it is not working.

    <script>
        alert(window.location.href);
    
        if (window.location.href.indexOf("drinks=spirits") > -1) {
alert("Hello! I am an alert box!!");
    
    }
    
    </script>

For example: I follow this order:

1- On the first visit, the URL is HTTP://example.com/drinks=spirits and it works.

2- Then I click on a filter, since I use ajax without reloading the page the URL changes to HTTP://example.com/drinks=spirits&price=less_10.

3- Then again when I remove the filter (again the page is not reloaded, it only removes the query) and the URL will be HTTP://example.com/drinks=spirits. Now the alert does not appear!

I am looking for a solution that shows the alert anytime users redirects to the HTTP://example.com/drinks=spirits

1 Answer 1

1

You need the hashchange event listener:

window.addEventListener("hashchange", function() {
  alert(window.location.href);

  if (window.location.href.indexOf("drinks=spirits") > -1) {
    alert("Hello! I am an alert box!!");
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it is not working for me. I try : window.addEventListener("hashchange", function() { alert(window.location.href); }); but it doesn't alert anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.