(window).load function dont work in refresh

361 Views Asked by At

I have a page where I have a function in window.onload to simulate a click on an element. This click can only happen when the page is completely loaded. It turns out that the function works when you first go to the page. After that it stops working. Close the function even without some elements on the screen.

Here is my simple function:

function clickOnMarker(){   
    alert('click on marker');
    var markerName = jQuery(".entry-title").text();
    jQuery( 'div[title="' + markerName + '"]' ).trigger( 'click' ); 
    alert('Fez clique no marker');  
}


 window.onload = function() { 
   clickOnMarker();
  };

The function reads the value of a title and clicks on a marker (HeroMap plugin - WordPress) to focus. It turns out that after running the sequences once, the function runs even without having the markers on the map.

Is there a way to control this behavior and always ensure that the script only runs if the markers are on the page? From what I saw, window.onload has this behavior and therefore my plan is ruined :).

Thank you for your help.

1

There are 1 best solutions below

0
PedroEstevesAntunes On

I ended up finding a solution a little out of the box :).

/************ GLOBAL VARIABELS **************/
var numAttempts = 15; // Number of attempts for the function's CallBack. Avoid Loop

/*********** CLICK ON MARKER ************/
function clickOnMarker(){

    var markerName = jQuery(".entry-title").text();  // Get text value (Title) on the Spots page

    if(numAttempts > 0){ // If that checks if there are no more attempts to CallBack the function clickOnMarker()

            if(jQuery( 'div[title="' + markerName + '"]' ).length > 0){ // If to Checks whether the element already exists in the page's DOM
                var markerName = jQuery(".entry-title").text();
                jQuery( 'div[title="' + markerName + '"]' ).trigger( 'click' ); 
                numAttempts = 10; // If the click was successful madein the marker the global variable must be reseted
                return;
            }else{
                callBackClickOnMarker(); // If the element does not exist in the DOM, it is called the CallBacK control function        
            }

    }else{
        numAttempts = 10; // If the number of attempts is exhausted the variable must be assigned the default value
        return;
    };  
};


/********** CALLBACK *************/
function callBackClickOnMarker(){
    // Function to call the function again with a delay of x mileseconds
    setTimeout(function(){
      clickOnMarker();
    }, 1500);   // Set the value in mileseconds of delay here for the action to be executed
    numAttempts -= 1; // 1 is subtracted to variable that controls the number of attempts
};


/*************** ON LOAD FUNCTION *************/
window.onload = function() { 
     clickOnMarker();
 };

It worked and is what it takes :)