Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading your JavaScript after an external JS get executed

I've a problem that is a bit tricky over here, I'm trying to apply a simple JQuery line of code that addClass to a div with class pop-up but the problem is that class pop_up is not accessible after jQuery(document).ready(function($){});

This class is actually added from an external JS and the pop_up functionality is also added from an external JS so I'm wondering

How To Add The Class using JQuery after the external JS get executed so pop_up class can be found using:

$('.pop_up');

What I've tried:

jQuery(document).ready(function($) {
    $('.pop_up').addClass('importantRule');
    $('.pop_up').toggleClass('importantRule');
});

this is not working as the external JS added the class somehow after .ready, so if you tried to print out $('.pop_up') it will be undefined.

I've also tried to look for the class using a constant class container of div.pop_up like this:

$('div.element').find('.pop_up').addClass('importantRule');

that didn't work either, I know for a fact the problem is with calling the function in .ready as some how the external JS get executed after it so,

is there away around this?

if not, is there a way to detect if all of external JS files are ready and loaded?

like image 261
Ahmad Sanie Avatar asked Feb 08 '23 01:02

Ahmad Sanie


2 Answers

You can have $(document).ready() multiple times in a page. The code gets run in the sequence in which it appears.

You can use the $(window).load() event for your code since this happens after the page is fully loaded and all the code in the various $(document).ready() handlers have finished running.

$(window).load(function(){
  //your code here
});
like image 92
KiwiJuicer Avatar answered Feb 10 '23 06:02

KiwiJuicer


One way is to use a setTimeout to check:-

function checkForElement() {

  setTimeout(function() {

    if ($('.pop_up').length) {
      $('.pop_up').addClass('importantRule');
    } else {
      checkForElement();
    }

  }, 100);

}

checkForElement();

This will wait for 100ms, then check. if its not there then it will wait again, and again, etc.

like image 21
BenG Avatar answered Feb 10 '23 08:02

BenG