Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appended HTML that contains javascript doesn't run, how can I make it run?

I'm appending some HTML containing javascript.

<td onclick="toggleDay('+data+',this,\'tue\');">T</td>

and

<img src="img/cross.png" onclick="deleteAlarm('+data+');">

These two pieces of code are in the big amount of HTML I'm appending.

They work fine if they are already there when the page loads but not when I'm appending.

What do you suggest me to do? Is it needed some sort request for the DOM to re-interpret the JavaScript after the append or?

EDIT:

Just some more info, I'm with this problem, because I'm adding some stuff with AJAX to the database, and on success I'm appending the html to where it needs to be. Kinda the same way SO does with the comments.

Edit2:

Even with all the discussion about it, thanks for the answers, got it working.

like image 393
fmsf Avatar asked Mar 03 '09 20:03

fmsf


1 Answers

I'd do it like this:

First add id attributes to your html:

<td id="toggleDayCell">T</td>

<img src="img/cross.png" id="crossImg">

Then have Javascript that runs on the onload event of the page and attaches to the events you're interested in.

In PrototypeJS, it might look like this:

Event.observe(window, 'load', function(){
  if( $('toggleDayCell') ) {
    Event.observe( $('toggleDayCell'), 'click', function(event){
      //do stuff here
    }
  }

  if( $('crossImg') ) {
    Event.observe( $('crossImg'), 'click', function(event) {
       //do stuff here
    }
  }
});

Using something like Prototype (or jQuery) is nice because it takes care of cross-browser compatibility.

like image 161
Mark Biek Avatar answered Oct 16 '22 15:10

Mark Biek