Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load jQuery functions on element load

Tags:

jquery

I have some jQuery code on each page of my application. I want to compress and put them all together in one file. Is it possible to load the jQuery only on a certain div load ? I tried adding a DIV id inside the body(ID=addProject) with the following jQuery code:

$("#addProject").ready(function() {
alert("test"); 
});

$("#addProject").pageload(function() {
alert("test"); 
});

 $("#addProject").on('pageload',function() {
alert("test"); 
});
like image 399
David Avatar asked Jan 31 '26 07:01

David


1 Answers

You can just wait till the doc is ready, then search for each element.

$(function() {
   if ($("#addProject").length > 0) {
      // execute some code for addProject
   }

   if ($("#deleteProject").length > 0) {
      // execute some code for deleteProject
   }
});

However it should be noted that if you're just trying to bind actions to elements in those divs (for example .on("click") events) then you can just go ahead and attempt to bind those even if the elements don't exist. It won't throw errors or anything. It just causes a minor performance hit depending on the size of the document.

like image 192
Jim Yarbro Avatar answered Feb 02 '26 00:02

Jim Yarbro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!