Jess Cauchi
Jess Cauchi

Reputation: 303

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(); 
        }
    })
});

Upvotes: 0

Views: 73

Answers (3)

Irfan Anwar
Irfan Anwar

Reputation: 1918

using adeneo's answer:

here is what matches your code:

$(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(); 
        }
    });
   $(window).on('hashchange', function() {
        if ( location.href == url ) {
            paintLine();
        }
   });
});

Upvotes: 0

adeneo
adeneo

Reputation: 318342

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

Upvotes: 2

spirit
spirit

Reputation: 3415

you can use setTimeout() function to run your function, for example every second:

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

   function test() {
      if (location.href == url) {
         paintLine();
      } else {
         setTimeout(test, 1000);
      }
   }
   test();
});

but what is your idea, behind your code? I sure there is more convenient ways to do your task.

Upvotes: 1

Related Questions