Christina Perla
Christina Perla

Reputation: 23

jQuery window.location.hash troubles

I have a one-page scroll type of site that uses a scroll-snapping plugin to snap from one section to the next. When each section is scrolled to, the hash changes (#1, #2, #3, etc).

I want to use the hash change to trigger an animation. So when testing the function I wrote, it only works when the page is refreshed. I can't post the site itself because it is local, but here is the code.

JS:

$(document).ready(function () {

//Trigger an animation based on hash location/URL
function hashChange() {
    alert("hashChange works!");
};
var hash = window.location.hash;
if (hash === '#3') {
    hashChange();
};

});

Any help would be greatly appreciated.


=======


UPDATE:

This is my updated code. But now it runs on every hash change (#1, #2, #3, #4).

function hashChange() {
    alert("hashChange works!");
};
window.addEventListener('hashchange', hashChange);
var hash = location.hash;
if (hash === '#3') {
    hashChange();
};

Does anyone know how to specify it? Also it is a one-page scroll that snaps to sections as you scroll. The hash changes as you scroll from section, but it doesn't trigger the alert I wrote.

Help!

Upvotes: 0

Views: 273

Answers (1)

mooiamaduck
mooiamaduck

Reputation: 2156

You can register an event listener for the hashchange event.

In your case:

function hashChange() {
  alert('hashChange works!');
}
window.addEventListener('hashchange', hashChange);

Upvotes: 2

Related Questions