Tallboy
Tallboy

Reputation: 13407

.on load not working

I have the most simple .on function i could write. it started off as trying to validate a form on load, then after many minutes of frustration I tried the following:

  $('p').on('load',function(){
     console.log("hello"); 
  });

This doesn't even work. I'm baffled. Ive tried it both IN and outside of $(document).ready(), neither work, and ive also checked console, there are no errors with my JS.

What could be causing this, its making me so mad

Upvotes: 2

Views: 1081

Answers (3)

Kevin B
Kevin B

Reputation: 95030

jQuery does not have a way of firing an event the first time a particular element becomes available. You can do it with setInterval, however there are usually much better ways to handle it depending in the situation.

setInterval(function(){
    $("p").not(".alreadyloaded").trigger("load").addClass("alreadyloaded");
},100);
$(document).on('load','p',function(){
    console.log("hello"); 
});

I do not suggest using this method if at all possible.

A better way of handling it would be to either use the callback of the event that is adding the p element (such as the success of the .load() or $.ajax) or by binding delegated events, such as $(document).on('click','p',function(){ alert('hello'); });

Upvotes: 1

Roko C. Buljan
Roko C. Buljan

Reputation: 206007

demo

You can always check for existence using length:

var par = $('p.paragraph'); // make it special with some ID or class


if(par.length){         // If your elements exists....
   alert(" I'm 'LOADED!' ;) ");
}

Upvotes: 1

oezi
oezi

Reputation: 51797

ps, divs and other elements don't have a load-event - thats only available on images, windows, frames and iframes.

Upvotes: 1

Related Questions