Ahmad Alsanie Ahmad Alsanie - 6 months ago 11
Javascript Question

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?

Answer

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