0

Okay how can i add function to injected elements(which that element dosent exist on first browser load). Please read through my example carefully , i hope you can understand.

For example: i go to www.website.com , when it loads it loads up "functions.js" and "other.js" , inside "functions.js" there's a code that injects a new div with ID when user click on a button.

The injection code as shown below:(functions.js --jquery)

$('a#button').click(function(){
    $('a#button').after('<div id="new">New div<br><a href="#" id="newdivlink">Another link</a></div>');
});

However there's another on click functions loaded in another js file which is "other.js" (loaded same time as function.js load).

Inside "other.js" has the code for the onclick function when the new div's link (#newdivlink) is clicked.

other.js :

$('a#newdivlink').click(function(){
  alert('you clicked on new div's link yay?');
});

But the problem is , the onclick function for the new div's link(#newdivlink) cant be executed as the script can't find the div (as it is being injected after i loads). Or is there some problems ?

P/S if you are asking why not combine both scripts , i don't want, as i want to try this technique out.

ETAN
  • 3,152
  • 6
  • 26
  • 35
  • You can use [`live()`](http://api.jquery.com/live/), [`delegate()`](http://api.jquery.com/delegate/) or [`bind()`](http://api.jquery.com/bind/) I think...but I read quickly and don't have the time to answer right now. Might be a help to you though. – David Thomas Oct 03 '11 at 09:28

3 Answers3

0

use live() for jQuery version < 1.7 or on() for version >= 1.7

simoncereska
  • 3,035
  • 17
  • 24
0

Try using 'live' instead of click:

$('a#newdivlink').live('click', function(){
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
0

What you probably need is jQuery.live.

$('a#newdivlink').live("click", function(){
    alert('you clicked on new div's link yay?');
});
klob
  • 657
  • 6
  • 13