Change style on hash change

Viewed 98

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.

1 Answers

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

Related