C O
C O

Reputation: 336

Check if page is loading in JavaScript?

I have a setInterval that selects an input and then submits the form with a click action. Now my problem is that my function clicks the button too many times. I tried adding a boolean to check if it has been clicked. No dice, page won't load. For some odd reason, the submit button doesn't work sometimes. I need the interval to be at 100 - 1000 just in case the page timeouts or lags.

How do I check to make sure it doesn't click again while the page is trying to load? The code can work fine if the interval is above 1000, but I need speed.

var pickSize = setInterval(function(){
    if (window.location.href.indexOf('/website/') == -1 && window.location.href.indexOf('/page.php') == -1) {
        if ($('input[value="236"]').attr("checked", true)) {
            $('.Add').click();
        }
    }
}, 1000);

Upvotes: 5

Views: 8975

Answers (3)

C O
C O

Reputation: 336

It's been years and the code is long gone but after revisiting this question I feel that I can offer some insight to those who are having issues with elements not being there.

The solution to this problem was to wait for the element to finish loading dynamically via an ajax call at the time. Once the element is loaded, you now have the ability to click that element.

This is actually something I personally face when creating automated testing and you will see in a lot of selenium code. Although, my code above was not selenium and it was just a regular script at the time. Consider using a library like selenium or puppeteer for any future automated testing.

Upvotes: 0

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

You can use onbeforeunload event to check if the page has started to navigate to another page:

var interval = setInterval(function(){
    if(window.location.href.indexOf("/website/") == -1 && window.location.href.indexOf("/page.php") == -1) {
        if($('input[value="236"]').attr("checked", true)) {
            $('.Add').click();
        }
    }
}, 1000);

window.addEventListener('beforeunload', function() {
  clearInterval(interval);
  console.log('Started to navigate away...');
});

However, it looks like you need to fix causes, but not consequences. Post your HTML and JS into another question like "why does my form submit only sometimes?" and let's try to understand the reason. It definitely does happen for some reason :)

Upvotes: 1

lyndact
lyndact

Reputation: 1

Try this:

var body = document.getElementsByTagName('BODY')[0];
// CONDITION DOES NOT WORK
if ((body && body.readyState == 'loading')) {
DoStuffFunction();
} else {
// CODE BELOW WORKS
if (window.addEventListener) {
    window.addEventListener('load', DoStuffFunction, false);
} else {
    window.attachEvent('onload',DoStuffFunction);
}
}

Upvotes: 0

Related Questions