Jump to content

Setting onclick with JavaScript in IE


boen_robot

Recommended Posts

I'm currently trying to make a form accessible, and so far I have all the controls working great with JS on, and degrading well with it off. With JS off, each control turns into a submit button, so that PHP could do whatever the JavaScript was supposed to do.However, there's a certain problem I'm facing, and you can guess by the title with which browser I'm having problems... IE of course. In order to avoid using event attributes (that is a good practice with JS, no?), I tryed to generate an "onclick" attribute to all controls, and turning their type to "button"s rather then "submit"s. Again for the sake of IE, what I really do is to rebuild all controls as buttons (as IE doesn't allow me to edit the "type" of a form field). But even with this new element, I'm unable to set an "onclick" with JavaScript. I checked with IE dev toolbar and it seems the "onclick" attribute is visible. It's just not executed for some reason. I tryed setting the same thing "manually" i.e. not with JavaScript, and it worked.Do you happen to know any way that an onclick can be set with JavaScript, and one that would work in IE too.Here's the HTML I'm working with. It's deliberatly compressed, so that JavaScript in all browsers isn't affected by whitespace nodes:

var js = new String('java script:');var jsRemove = new String('remove(');var jsInsertAt = new String('insertAt(');var jsMoveUp = new String('moveUp(');var jsMoveDown = new String('moveDown(');var jsCb = new String(')');var tableContents = document.getElementsByTagName('table').item(0).tBodies[0];function addEntry() {	var entries = tableContents.childNodes.length;	var newRow = document.createElement('tr');	var newHeader = document.createElement('th');	var newCell = document.createElement('td');	var newInput = document.createElement('input');	var newControlCell = newCell.cloneNode(true);	newControlCell.className = 'control';	var newControlLink = newInput.cloneNode(true);	newControlLink.setAttribute('type','button');	newControlLink.setAttribute('name',new String('prices/[').concat(entries,']'));		newInput.setAttribute('type','text');	newInput.setAttribute('size',12);	newHeader.appendChild(newInput.cloneNode(true));	newHeader.childNodes[0].value = 'Гориво';	var entryRef = new String('entry[').concat(entries,']');	var fuelRef = entryRef.concat('[fuel]');	newHeader.childNodes[0].setAttribute('name',fuelRef);	newRow.appendChild(newHeader);	newCell.appendChild(newInput.cloneNode(true));	newCell.childNodes[0].value = '0.0';	var priceRef = entryRef.concat('[price]');	newCell.childNodes[0].setAttribute('name',priceRef);	newRow.appendChild(newCell);		newControlLinkRemove = newControlLink.cloneNode(true);	newControlLinkRemove.value = '−';	newControlLinkRemove.title = 'Премахни';	newControlLinkRemove.setAttribute('onclick',/*js.concat(jsRemove,entries,jsCb)*/'java script:alert("testing...");');		newControlLinkMoveUp = newControlLink.cloneNode(true);	newControlLinkMoveUp.value = '▲';	newControlLinkMoveUp.title = 'Премести нагоре';	if (entries != 0) {		newControlLinkMoveUp.setAttribute('onclick',js.concat(jsMoveUp,entries,jsCb));	}else {		newControlLinkMoveUp.disabled = true;	}		newControlLinkInsert = newControlLink.cloneNode(true);	newControlLinkInsert.value = '+';	newControlLinkInsert.title = 'Копирай';	newControlLinkInsert.setAttribute('onclick',js.concat(jsInsertAt,entries,jsCb));		newControlLinkMoveDown = newControlLink.cloneNode(true);	newControlLinkMoveDown.value = '▼';	newControlLinkMoveDown.title = 'Премести нагодлу';	newControlLinkMoveDown.disabled = true;	newControlCell.appendChild(newControlLinkRemove);	newControlCell.appendChild(newControlLinkMoveUp);	newControlCell.appendChild(document.createElement('br'));	newControlCell.appendChild(newControlLinkInsert);	newControlCell.appendChild(newControlLinkMoveDown);		newRow.appendChild(newControlCell);	tableContents.appendChild(newRow);	if (entries > 0) {		tableContents.childNodes[entries - 1].cells[2].childNodes[4].setAttribute('onclick',js.concat(jsMoveDown,entries - 1,jsCb));		tableContents.childNodes[entries - 1].cells[2].childNodes[4].disabled = false;	}else {		tableContents.childNodes[entries - 1].cells[2].childNodes[4].disabled = true;	}}function remove(entry) {	tableContents.deleteRow(entry);	var entriesAfter = tableContents.childNodes.length;	for (i=0;i<entriesAfter;i++) {		tableContents.childNodes[i].cells[2].childNodes[0].setAttribute('onclick',js.concat(jsRemove,i,jsCb));		if (i != 0) {			tableContents.childNodes[i].cells[2].childNodes[1].setAttribute('onclick',js.concat(jsMoveUp,i,jsCb));			tableContents.childNodes[i].cells[2].childNodes[1].disabled = false;		}else {			tableContents.childNodes[i].cells[2].childNodes[1].disabled = true;		}		tableContents.childNodes[i].cells[2].childNodes[3].setAttribute('onclick',js.concat(jsInsertAt,i,jsCb));		if (i < entriesAfter - 1) {			tableContents.childNodes[i].cells[2].childNodes[4].setAttribute('onclick',js.concat(jsMoveDown,i,jsCb));			tableContents.childNodes[i].cells[2].childNodes[4].disabled = false;		}else {			tableContents.childNodes[i].cells[2].childNodes[4].disabled = true;		}	}}function moveUp(entry) {	var entries = tableContents.childNodes.length;	var pEntry = entry - 1;	oldRow = tableContents.childNodes[pEntry].cloneNode(true);	newRow = tableContents.childNodes[entry].cloneNode(true);	oldRow.childNodes[0].childNodes[0].name = new String('entry[').concat(entry,'][fuel]');	oldRow.childNodes[1].childNodes[0].name = new String('entry[').concat(entry,'][price]');	oldRow.childNodes[2].childNodes[0].setAttribute('onclick',js.concat(jsRemove,entry,jsCb));	oldRow.childNodes[2].childNodes[1].setAttribute('onclick',js.concat(jsMoveUp,entry,jsCb));	oldRow.childNodes[2].childNodes[1].disabled = false;	oldRow.childNodes[2].childNodes[3].setAttribute('onclick',js.concat(jsInsertAt,entry,jsCb));	if (entry != entries - 1) {		oldRow.childNodes[2].childNodes[4].setAttribute('onclick',js.concat(jsMoveDown,entry,jsCb));	}else {		oldRow.childNodes[2].childNodes[4].disabled = true;	}		newRow.childNodes[2].childNodes[0].setAttribute('onclick',js.concat(jsRemove,pEntry,jsCb));	if (pEntry != 0) {		newRow.childNodes[2].childNodes[1].setAttribute('onclick',js.concat(jsMoveUp,pEntry,jsCb));	}else {		newRow.childNodes[2].childNodes[1].disabled = true;	}	newRow.childNodes[2].childNodes[3].setAttribute('onclick',js.concat(jsInsertAt,pEntry,jsCb));	newRow.childNodes[2].childNodes[4].setAttribute('onclick',js.concat(jsMoveDown,pEntry,jsCb));	newRow.childNodes[2].childNodes[4].disabled = false;	newRow.childNodes[0].childNodes[0].name = new String('entry[').concat(pEntry,'][fuel]');	newRow.childNodes[1].childNodes[0].name = new String('entry[').concat(pEntry,'][price]');	tableContents.replaceChild(newRow,tableContents.childNodes[pEntry]);	tableContents.replaceChild(oldRow,tableContents.childNodes[entry]);}function insertAt(entry) {	var pEntry = entry + 1;	var entries = tableContents.childNodes.length;	var newRow = tableContents.childNodes[entry].cloneNode(true);	if (entry != entries - 1) {		tableContents.insertBefore(newRow,tableContents.childNodes[pEntry]);	}else {		tableContents.appendChild(newRow);	}	for(i=0;i<entries + 1;i++) {		tableContents.childNodes[i].cells[2].childNodes[0].setAttribute('onclick',js.concat(jsRemove,i,jsCb));		if (i != 0) {			tableContents.childNodes[i].cells[2].childNodes[1].setAttribute('onclick',js.concat(jsMoveUp,i,jsCb));		}		tableContents.childNodes[i].cells[2].childNodes[3].setAttribute('onclick',js.concat(jsInsertAt,i,jsCb));		if (i < entries) {			tableContents.childNodes[i].cells[2].childNodes[4].setAttribute('onclick',js.concat(jsMoveDown,i,jsCb));		}	}}function moveDown(entry) {	var entries = tableContents.childNodes.length;	var pEntry = entry + 1;	oldRow = tableContents.childNodes[pEntry].cloneNode(true);	newRow = tableContents.childNodes[entry].cloneNode(true);	oldRow.childNodes[0].childNodes[0].name = new String('entry[').concat(entry,'][fuel]');	oldRow.childNodes[1].childNodes[0].name = new String('entry[').concat(entry,'][price]');		oldRow.childNodes[2].childNodes[0].setAttribute('onclick',js.concat(jsRemove,entry,jsCb));	if (entry != 0) {		oldRow.childNodes[2].childNodes[1].setAttribute('onclick',js.concat(jsMoveUp,entry,jsCb));		oldRow.childNodes[2].childNodes[1].disabled = false;	}else {		oldRow.childNodes[2].childNodes[1].disabled = true;	}	oldRow.childNodes[2].childNodes[3].setAttribute('onclick',js.concat(jsInsertAt,entry,jsCb));	oldRow.childNodes[2].childNodes[4].setAttribute('onclick',js.concat(jsMoveDown,entry,jsCb));	oldRow.childNodes[2].childNodes[4].disabled = false;		newRow.childNodes[2].childNodes[0].setAttribute('onclick',js.concat(jsRemove,pEntry,jsCb));	newRow.childNodes[2].childNodes[1].setAttribute('onclick',js.concat(jsMoveUp,pEntry,jsCb));	newRow.childNodes[2].childNodes[1].disabled = false;	newRow.childNodes[2].childNodes[3].setAttribute('onclick',js.concat(jsInsertAt,pEntry,jsCb));	if (pEntry < entries - 1) {		newRow.childNodes[2].childNodes[4].setAttribute('onclick',js.concat(jsMoveDown,pEntry,jsCb));		newRow.childNodes[2].childNodes[4].disabled = false;	}else {		newRow.childNodes[2].childNodes[4].disabled = true;	}	newRow.childNodes[0].childNodes[0].name = new String('entry[').concat(pEntry,'][fuel]');	newRow.childNodes[1].childNodes[0].name = new String('entry[').concat(pEntry,'][price]');	tableContents.replaceChild(newRow,tableContents.childNodes[pEntry]);	tableContents.replaceChild(oldRow,tableContents.childNodes[entry]);}var entries = tableContents.childNodes.length;for(i=0;i<entries;i++) {	newControlLink = document.createElement('input');	newControlLink.setAttribute('type','button');	newControlLink.setAttribute('name',new String('prices/[').concat(i,']'));	tableContents.childNodes[i].cells[2].replaceChild(newControlLink.cloneNode(true),tableContents.childNodes[i].cells[2].childNodes[0]);	tableContents.childNodes[i].cells[2].replaceChild(newControlLink.cloneNode(true),tableContents.childNodes[i].cells[2].childNodes[1]);	tableContents.childNodes[i].cells[2].replaceChild(newControlLink.cloneNode(true),tableContents.childNodes[i].cells[2].childNodes[3]);	tableContents.childNodes[i].cells[2].replaceChild(newControlLink.cloneNode(true),tableContents.childNodes[i].cells[2].childNodes[4]);		tableContents.childNodes[i].cells[2].childNodes[0].value = '−';	tableContents.childNodes[i].cells[2].childNodes[1].value = '▲';	tableContents.childNodes[i].cells[2].childNodes[3].value = '+';	tableContents.childNodes[i].cells[2].childNodes[4].value = '▼';	tableContents.childNodes[i].cells[2].childNodes[0].innerHTML = '−';	tableContents.childNodes[i].cells[2].childNodes[1].innerHTML = '▲';	tableContents.childNodes[i].cells[2].childNodes[3].innerHTML = '+';	tableContents.childNodes[i].cells[2].childNodes[4].innerHTML = '▼';	tableContents.childNodes[i].cells[2].childNodes[0].setAttribute('onclick',js.concat(jsRemove,i,jsCb));	if (i != 0) {		tableContents.childNodes[i].cells[2].childNodes[1].setAttribute('onclick',js.concat(jsMoveUp,i,jsCb));	}else {		tableContents.childNodes[i].cells[2].childNodes[1].disabled = true;	}	tableContents.childNodes[i].cells[2].childNodes[3].setAttribute('onclick',js.concat(jsInsertAt,i,jsCb));	if (i < entries - 1) {		tableContents.childNodes[i].cells[2].childNodes[4].setAttribute('onclick',js.concat(jsMoveDown,i,jsCb));	}else {		tableContents.childNodes[i].cells[2].childNodes[4].disabled = true;	}}document.getElementById('addEntry').href = js.concat('addEntry()');

(the problematic part is within the "for" loop in the end, though other parts would be affected by changes in it.I was really hoping I could pull that off without help, but all of my attempts have failed. ".setAttribute()", ".onclick"... both work perfectly in Firefox and Opera, but not in IE. And I'd really love not to put those attributes in the form.I'm willing to rethink my approach and "onsubmit" send the form to a single function that will decide what to do based on the button that was clicked. This however begs the question "how will I know which button was pressed?".If all else fails, I guess I'll be hardcoding the references to "onclick" attributes, but even then, when I add entries (i.e. table rows) with the "+" buttons or the link below, I'd need a way to adjust the "onclick" as each function takes one argument, different depending on the row of the table. So the question would remain even this case. How can set the "onclick" attribute on elements created with JavaScript?

Link to comment
Share on other sites

Your page links to 2 JavaScripts: editTable.js and newWindow.js... Where's the other (I'm guessing newWindow.js), or do we need it? (If not, I'll need to know for certain which to remove from the page.)"If all else fails", would it work to use innerHTML modifications?Also, could you modify the page with info from PHP/ASP/etc. (maybe by setting a hidden field, on submit, to identify the button clicked - not sure if that would work)?

Link to comment
Share on other sites

[...] I'm unable to set an "onclick" with JavaScript. I checked with IE dev toolbar and it seems the "onclick" attribute is visible. It's just not executed for some reason. I tryed setting the same thing "manually" i.e. not with JavaScript, and it worked.Do you happen to know any way that an onclick can be set with JavaScript, and one that would work in IE too.
Have a look at this info on addEventListener and attachEvent. It includes an example of code that works in both IE and non-IE.
Link to comment
Share on other sites

Your page links to 2 JavaScripts: editTable.js and newWindow.js... Where's the other (I'm guessing newWindow.js), or do we need it? (If not, I'll need to know for certain which to remove from the page.)"If all else fails", would it work to use innerHTML modifications?Also, could you modify the page with info from PHP/ASP/etc. (maybe by setting a hidden field, on submit, to identify the button clicked - not sure if that would work)?
newWindow.js is the one you can remove and it's not needed for this page.Sure, innerHTML is acceptable, and as far as I'm aware, it's even faster in most cases. But the main problem would remain - actually detecting the click.I generate the HTML with PHP that is under my control, but as I said, the form already degrades well with JS off. The problem is using JS to replace the server doings.@Reg Edit, thanks, I'll look into that, and write as to how it goes.
Link to comment
Share on other sites

OK. I tried turning my

tableContents.childNodes[i].cells[2].childNodes[0].setAttribute('onclick','remove(' + i + ')');

(or should I say - the sort of)into

tableContents.childNodes[i].cells[2].childNodes[0].onclick = remove(i);

but that executes the function, leaving the table empty.I need to not only reference the function, but pass an argument to it too and it seems addEventListener can't do it too... hmm... I've heared of anonymous functions? How can I create an anonymous function within the ".onclick" that would just reference the other appropriate function with the right argument?BTW, I've slightly restructured my HTML to use <button type="submit"/> instead of <input type="submit"/> as <button/> allows me to send a value AND have a different text shown which is exactly what I want. I'll rework my functions accordingly, but before I do that, I still need to solve this ".onclick" thingy.[edit]Talked too soon. IE doesn't send the value of the button. Instead, it sends its contents, which is exactly what I was trying to avoid. All right... I guess it's back to <input type="submit"/> on the markup level, and more check on the server level.[/edit][edit]Is it done like shown in the last example from the above page? i.e.

.onclick = function(){remove(i);};

?OK. That's it I guess. After some reading on QuirksMode, I tryed

tableContents.childNodes[i].cells[2].childNodes[0].onclick = function() {return 'remove('+i+');';};

but that doesn't seem to work either.... boy... a new challenge. Actually passing argument to the event function. I mean, what use are functions if you can't pass arguments to them?[/edit]

Link to comment
Share on other sites

[...] I mean, what use are functions if you can't pass arguments to them?
You can use the mouseEvent object that's passed to the event handler to identify, among other things, the element that raised the event. You should be able to use that rather than passing an argument. I didn't study your code in detail but perhaps you could set your value into another attribute of the button if you need more than the id.
<html><head><script type="text/javascript">	function onButtonClicked(e)	{		if (e.target)		{			alert(e.target.id);		}		else if (e.srcElement)		{			alert (e.srcElement.id);		}	}	function addMyListener(el)	{		if (el.addEventListener)		{		  el.addEventListener('click', onButtonClicked, false); 		} 		else if (el.attachEvent)		{		  el.attachEvent('onclick', onButtonClicked);		}	}</script></head><body>	<input type="button" value="button 1" id="button1"></input>	<input type="button" value="Add listener" onclick="addMyListener(document.getElementById('button1'))"></input></body></html>

Link to comment
Share on other sites

Hm... that's a new approach I'll have to get used to...What type of object exactly is the "e" in your example? DOM Element? And which one? The element which initiated the event (i.e. that was clicked)?Also, do the old way* properties also get this argument automatically like those seem to? What's the case with them if they do?*"element.onclick = functionName;"Let me show a simplified (indented) version of what I have right now just in case:

<form action="?uri=prices/" method="post" onsubmit="java script:alert('submitted')">		  <table>			<caption>Това са цените на горивата при нас</caption>			<thead>			  <tr>				<th>Гориво</th>				<th>Цена (лв./л.)</th>				<td class="control"></td>			  </tr>			</thead>			<tbody>			  <tr>				<th>				  <input name="entry[0][fuel]" size="12" value="Бензин А-92" />				</th>				<td>				  <input name="entry[0][price]" size="12" value="1.91" />				</td>				<td class="control">				  <input type="submit" name="action[0]" value="−" title="Премахни" />				  <input type="submit" name="action[0]" value="▲" title="Премести нагоре" disabled="disabled" />				  <br />				  <input type="submit" name="action[0]" value="+" title="Копирай" />				  <input type="submit" name="action[0]" value="▼" title="Премести надолу" />				</td>			  </tr>			  <tr>				<th>				  <input name="entry[1][fuel]" size="12" value="Бензин А-95" />				</th>				<td>				  <input name="entry[1][price]" size="12" value="1.97" />				</td>				<td class="control">				  <input type="submit" name="action[1]" value="−" title="Премахни" />				  <input type="submit" name="action[1]" value="▲" title="Премести нагоре" />				  <br />				  <input type="submit" name="action[1]" value="+" title="Копирай" />				  <input type="submit" name="action[1]" value="▼" title="Премести надолу" />				</td>			  </tr>			  <tr>				<th>				  <input name="entry[2][fuel]" size="12" value="Газ" />				</th>				<td>				  <input name="entry[2][price]" size="12" value="0.99" />				</td>				<td class="control">				  <input type="submit" name="action[2]" value="−" title="Премахни" />				  <input type="submit" name="action[2]" value="▲" title="Премести нагоре" />				  <br />				  <input type="submit" name="action[2]" value="+" title="Копирай" />				  <input type="submit" name="action[2]" value="▼" title="Премести надолу" disabled="disabled" />				</td>			  </tr>			</tbody>		  </table>		  <div>			<p>			  <input type="submit" name="action" value="Добави гориво" id="addEntry" />			</p>			<script type="text/javascript" src="/_scripts/editTable.js"></script>			<input type="submit" name="action" value="Запази промените" />		  </div>		</form>

That sort of HTML being preserved on the markup level, I don't mind anything in JavaScript :) .

Link to comment
Share on other sites

Hm... that's a new approach I'll have to get used to...What type of object exactly is the "e" in your example? DOM Element? And which one? The element which initiated the event (i.e. that was clicked)? [...]
That depends! In the non-IE world of DOM2, where you've used addEventListener, its a MouseEvent object. But in the IE world of the IE event model, where you've used attachEvent, its an event object!BTW if you're not using Firebug etc and you want a quick way of knowing the type of object e in Firefox, you can use alert(e) to display it, and would see "[object MouseEvent]" in this case.
[...] Also, do the old way* properties also get this argument automatically like those seem to? What's the case with them if they do?*"element.onclick = functionName;"
Yes if you pass the event argument when you set the attribute value:
	<input id="old" type="button" value="old" onclick="onButtonClicked(event)"></input>

There's an interesting page here on this subject, including how anonymous functions relate to inline event handlers (i.e., those assigned via html attributes) .

Link to comment
Share on other sites

OMFG. I just remembered why I always avoid JavaScript in general. Too much information at once... my head is going to explode! I haven't had that feeling for a long time now. The last time I think was when I realized how DOM and OOP in general works.Before anything, I'm trying not to use "on*" HTML attributes, so please, bare with me, showing future examples without such, please.So... let me try to review what I have gathered so far and please correct any errors you see.

element.onclick = functionName;

refers to a function named "functionName" associated with the onclick event. Within the "functionName" function, a single argument is always available which if used points to ... the current window object in IE... and the element which initiated the event in non-IE... the same rules also applying for the "this" keyword used within the function... and it's pretty much the same deal with element.addEventListener() for non-IE or element.attachEvent() for IE?OK... so... let's simplify it even further... in the following example:

<html><head><script type="text/javascript">function doSomething(e) {alert(e);alert(this);}</script></head><body>	<input type="button" value="button 1" id="button1"/>	<script type="text/javascript">???</script></body></html>

How would you attach the doSomething() function to "button1" without using the "onclick" attribute on it and within the second script element? What should the "e" and "this" object contain in which browser, and how to ensure cross browser compatability? The samples you gave are great, but they're just too much...Sorry to ask all this bunch of silly questions, but bare with me that I'm in a land I haven't been before.... god, I wish I could have just used setAttribute() and be over with it... it would have been very simple... again IE messes everything up.

Link to comment
Share on other sites

[...] Sorry to ask all this bunch of silly questions, but bare with me that I'm in a land I haven't been before.... god, I wish I could have just used setAttribute() and be over with it... it would have been very simple... again IE messes everything up.
:) First a bit of context:
  • The "old" way is to declare onclick etc in html element declarations. You are trying to avoid this old way; I want to make the point that, since the reason for avoiding it is better separation from html, you would not really want to set html attribute values in script either, as that would defeat the first purpose.
  • The slightly less old way, from DOM0, is to set object properties in script (button1.onclick etc);
  • The current "new" way, established under DOM2 in 2000, is to use addEventListener, which gives more fine-grain control (and requires the IE support trickery I showed in the examples above).

I will answer your question by setting button1.onclick in script as you've asked:

document.getElementById('button1').onclick = doSomething;

If you try this, you'll see that the values in doSomething are:

(not really code but it aligns my columns somewhat! Is there a better way to do this?)IE?	  e								this----	  ----------------------	  ---------------------------------y		 undefined					button1 objectn		 MouseEvent object	   button1 object

In other words, if you use that approach, this is the element that raised the event, and so you don't need to find it in an event argument. I will pause there for this post to keep it simple, and await your reaction :) --just keep in mind that there are reasons to use addEventListener instead, which you can read up on when you feel the need.

Link to comment
Share on other sites

So you mean to say that with

document.getElementById('button1').onclick = doSomething;

in both IE and non-IE, the value of "this" within the funciton is the element that initiated the event?!?! I thought it's a document.window object with IE.But that's great news!!! This means I can easily replace what I previously needed as an argument by just adding

var entry = this.parentNode.parentNode.rowIndex;

at the top of each function and removing the argument!I'm not at my computer now, but when I am, I'm certainly going to try that out. Thanks.BTW, I'm not going to use addEventListener() not because of anything else, but because I simply don't need it's advanced capabilities with this one. A single onclick event handler is all I need.Just to verify for future's sake, the situation with "e" and "this" is the same with addEventListener() as with the event properties, right? That is, if you've used

if(document.getElementById('button1').addEventListener) {document.getElementById('button1').addEventListener('click',doSomething,false);}else if (document.getElementById('button1').attachEvent) {document.getElementById('button1').attachEvent('click',doSomething);}

the results from the alerts were going to be the same, right?[edit]@aspnetguy Fine by me. Compatability for anything below IE6 is not a must.[/edit]

Link to comment
Share on other sites

So you mean to say that with
document.getElementById('button1').onclick = doSomething;

in both IE and non-IE, the value of "this" within the funciton is the element that initiated the event?!?!

Yes.
[...] I thought it's a document.window object with IE [...].
It can be at other times: more on one of them below!
[...] Just to verify for future's sake, the situation with "e" and "this" is the same with addEventListener() as with the event properties, right? That is, if you've used
if(document.getElementById('button1').addEventListener) {document.getElementById('button1').addEventListener('click',doSomething,false);}else if (document.getElementById('button1').attachEvent) {document.getElementById('button1').attachEvent('click',doSomething);}

the results from the alerts were going to be the same, right?

Not quite... the results are unchanged in non-IE, but they change in IE:
  • e is no longer undefined, and is now an event object (whose properties include the element that raised the event--see the example earlier)
  • this is now the window object

Also note that the event names are subtly different for IE (onclick, not click, for attachEvent).

Link to comment
Share on other sites

Yes.It can be at other times: more on one of them below!Not quite... the results are unchanged in non-IE, but they change in IE:
  • e is no longer undefined, and is now an event object (whose properties include the element that raised the event--see the example earlier)
  • this is now the window object

Also note that the event names are subtly different for IE (onclick, not click, for attachEvent).

OK. I understand now. One more reason I'll be using the event properties for a while and avoid those two methods... at least until IE supports addEventListener() which could be quite some time.But if it was a must that I use attachEvent(), I suppose I could use the.... oh no. Looking at the reference on W3Schools, there seems to be no property that would return the element in IE. I see three (target, currentTarget, relatedTarget) that could possibly be used, but the reference says none are available in IE. How would I be detecting the element that was clicked then? [edit]Cancel that. Saw the previous example (and the MSDN reference). The srcElement property it is then.[/edit]
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...