setAttribute('onclick', 'alert(this.id)') works for existing element but not for ones dynamically created

VERIFIED DUPLICATE of bug 7997

Status

()

Core
Event Handling
P3
normal
VERIFIED DUPLICATE of bug 7997
19 years ago
18 years ago

People

(Reporter: Martin Honnen, Assigned: joki (gone))

Tracking

Trunk
Other
Other
Points:
---

Firefox Tracking Flags

(Not tracked)

Details

Attachments

(1 attachment)

(Reporter)

Description

19 years ago
I can - using setAttribute - add an event handler, for instance onclick, to 
elements existing in the HTML source but if I try the same on a dynamically 
created element the attribute is set but no event handler is created/fires.
That seems to be a bug. Either I can create event handlers by setting the 
string attribute or I can't but it can't be right that it works for some 
elements and for others not.

I attach an example where you can successfully add an event handler to an 
existing BUTTON element while creating a BUTTON and then setting the event 
handler fails.

<HTML>
<HEAD>
<STYLE>

</STYLE>
<SCRIPT>
function createButton (id, content) {
  var button = document.createElement('BUTTON');
  button.appendChild(document.createTextNode(content));
  document.body.appendChild(button);
}
function addOnClickAttribute (id, onclick) {
  var el = document.getElementById(id);
  el.setAttribute('onclick', onclick);
}
function init () {
  addOnClickAttribute('button1', 'alert(this.id + \' clicked.\')');
  createButton('button2', 'button 2 dynamically created');
  addOnClickAttribute('button2', 'alert(this.id + \' clicked.\')');
}
</SCRIPT>
</HEAD>
<BODY ONLOAD="init()">
<BUTTON ID="button1">
button 1
</BUTTON>
<BR>
</BODY>
</HTML>
(Reporter)

Comment 1

19 years ago
Created attachment 6684 [details]
bug demo (try the buttons the first fires onclick the second not)
(Assignee)

Comment 2

19 years ago

*** This bug has been marked as a duplicate of 7997 ***
Status: NEW → RESOLVED
Last Resolved: 19 years ago
Resolution: --- → DUPLICATE
(Assignee)

Comment 3

18 years ago
By the was, for verification purposes the script needs to be modified so that 
the first function is:

function createButton (id, content) {
  var button = document.createElement('BUTTON');
  button.appendChild(document.createTextNode(content));
  button.setAttribute('id', id);
  document.body.appendChild(button);
}

otherwise the id attribute isn't set and it doesn't work.

Comment 4

18 years ago
Mass update:  changing qacontact to ckritzer@netscape.com
QA Contact: janc → ckritzer

Comment 5

18 years ago
Updating QA Contact.
QA Contact: ckritzer → lorca

Comment 6

18 years ago
Verified dupe.
Status: RESOLVED → VERIFIED
You need to log in before you can comment on or make changes to this bug.