Jess Cauchi Jess Cauchi - 3 months ago 14
jQuery Question

how to get jquery to run repeatedly

I currently have a piece of jquery code that looks for a specific URL (with an anchor at the end) and runs a function if it has a match. The code only runs once, if this is the first URL loaded. Is it possible to have the following code running until it has a match?

$(document).ready(function(){
var url = "https://s3-eu-west-1.amazonaws.com/datahealthcheck16-test/index.html#backup-section-3";
$(function(){
if (location.href==url){
paintLine();
}
})
});

Answer

It only runs the first time, because changing the hash does not fire the DOM ready handler again, it does however fire the hashchange event.

$(window).on('hashchange', function() {
    if ( window.location.hash === '#backup-section-3' ) {
        paintLine();
    }
}).trigger('hashchange'); // fire on first load as well

Note that the window is always available, and does not need a DOM ready handler