views:

34

answers:

2

So here is the jQuery snippet I am using to create a div that I want to click on

$("#someID").after('<div style="cursor:pointer; text-decoration:underline; display:inline;" onClick="alert(\'It Worked\');">Details</div>');

This Works in FireFox without any problems its just IE that doesn't fire the event. The div is added right after #someID but the onclick doesn't work.

+2  A: 

You should add the click handler using jQuery's click method, like this:

$('<div style="cursor:pointer; text-decoration:underline; display:inline;">Details</div>')
    .click(function() { alert('It Worked'); })
    .insertAfter('#someID');

This will work, and will also be much faster. (The browser won't need to fire up a Javascript parser)

SLaks
this is not foolproof. see my answer.
Moin Zaman
@Moin: Yes, it is. What are you talking about?
SLaks
So I had tried using after and doing much the same thing above and it didn't work but switched to insertAfter and the solution above and got it to work thanks.
runxc1 Bret Ferrier
A: 

use .live() or .delegate() to bind events to elements created after page load (in the future).

Moin Zaman
I would agree with this, since live() will bind the listener whether or not the referenced element is already in the DOM or not. I have all but abandoned using click().
exoboy