3

I am looking for a way to change part of style by changing the hash. Let me explain by an example:

  1. The current URL is:
    example.com/drinks/?all-drinks=drinks

  2. Then I click on the checkbox and the URL will change to :
    example.com/drinks/?all-drinks=drinks&drinks=spirits-drinks

I want to change style of a class.

I try the following code but it is not working:

<script>
$( window ).on( 'hashchange', function( e ) {
    console.log( 'hash changed' );
} );
</script>

In fact, every time the hash changes nothing appears in the console.

Sallar Rabiei
  • 630
  • 1
  • 12
  • 33

1 Answers1

1

Window: hashchange event [docs]

The hashchange event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol).

Sine you're trying to detect ?all-drinks=drinks to ?all-drinks=drinks&drinks=spirits-drinks this is not covered in hashchange


  1. You could extend locationchange as @aljgom explains here: in his answer.

    Example JsFiddle

  2. Or the onpopstate event, explained here

  3. Or some monkey patching to 'fake' some sort of onpushstate explained in this answer

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • I try `` in `` , but in console nothing appear. – Sallar Rabiei Apr 24 '21 at 15:52
  • Please Read the complete answer, you'll need to extend some, it's wel explained in the answer. – 0stone0 Apr 24 '21 at 15:53
  • 1
    @M.SallarRabiei I've added a JSFiddle link with a small example. – 0stone0 Apr 24 '21 at 16:01
  • I appreciate your kindness @0stone0 , in the `JsFiddle` you add, it always change the URL, but I want to `check the current URL` in any changes by `ajax`, and if URL is equal to `X` it contains a specific style, and if URL is equal to `Y` contain the specific style. – Sallar Rabiei Apr 24 '21 at 16:52
  • 1
    Does [this](https://jsfiddle.net/Lb7kctud/3/) help? Otherwise, please elaborate the question. – 0stone0 Apr 24 '21 at 17:12
  • Many thanks, I am a little bit confused, as I mentioned in question, I just want to check URL live, and if URL equals `https://example.com/drinks/?all-drinks=drinks` change color, and if URL equal `https://example.com/drinks/?all-drinks=drinks&drinks=spirits-drinks` use another color for the element. In the JSFiddle it generates URL, and I do not completely understand how to use that. – Sallar Rabiei Apr 24 '21 at 18:35
  • 1
    Thanks, the first link you provide inspire me and I finally find a way. many thank @0stone0 – Sallar Rabiei Apr 24 '21 at 22:13