View Full Version : Example of DOM event attachment if possible
Falkon303
02-21-2009, 08:38 AM
Hmm... anyone out there have a very simple example of DOM event attachment in action?
I mean super simple, like perhaps if I wanted a mouseover of one element to affect the innerhtml of another.
I'd love to see a basic event handler/attachment
- Ben
jscheuer1
02-21-2009, 02:57 PM
I'm not sure what the question is exactly. Say you create two span elements and a function:
var a = document.createElement('span'),
b = a.cloneNode(false);
function f(){b.firstChild.nodeValue += 'Hello World! ';}
add in some text nodes:
a.appendChild(document.createTextNode('Mouse Me!'));
b.appendChild(document.createTextNode('\xa0'));
attach/add function f to span a as a mouseover listener:
if (window.addEventListener)
a.addEventListener('mouseover', f, false);
else if (window.attachEvent)
window.attachEvent('onmouseover', f);
and Bob's your uncle. But let's wrap it all up in a function to execute when the page loads so that it can actually do something (in this case append its elements to the body):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function myload(){
var a = document.createElement('span'), b = a.cloneNode(false);
function f(){b.firstChild.nodeValue += 'Hello World! ';}
a.appendChild(document.createTextNode('Mouse Me!'));
b.appendChild(document.createTextNode('\xa0'));
if (window.addEventListener)
a.addEventListener('mouseover', f, false);
else if (window.attachEvent)
a.attachEvent('onmouseover', f);
document.body.appendChild(a);
document.body.appendChild(b);
}
if (window.addEventListener)
window.addEventListener('load', myload, false);
else if (window.attachEvent)
window.attachEvent('onload', myload);
</script>
</head>
<body>
</body>
</html>
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.