PDA

View Full Version : I wonder if there is a DOM attribute for javascript events



Dal
07-21-2008, 10:41 PM
Im sure the title didnt really explain so here goes...:confused:


I can access a html element via document.getElementById('something') and I can reach DOM attributes from this so;



document.getElementById('something').style.display
//or
document.getElementById('something').id
document.getElementById('something').innerHTML
//ect...


Im wondering if I can access the onclick and other events which are written to the element ie;



document.getElementById('something').onclick = "mouseclickfunc(mypassed,variables)";
//or
document.getElementById('something').onmouseover = "somefunc(some,thing);";
//ect...


which would write to the document;


<div id="something" onclick="mouseclickfunc(mypassed,variables);" onmouseover="somefunc(some,thing);">


I need to replace the function names for onclick and other events as the element roles change in another part of the site. I could use php to search the html and replace that way but I thought Id check to see if this was available. I know that the document.getElementById('something').onclick is used for actually applying an event to the element so I image its not going to be what my example.

Anyone know what I mean and if it can be done?
:D
Thanks
Dal

rangana
07-22-2008, 01:13 AM
Maybe you mean something like this:


<script type="text/javascript">
window.onload=function()
{
var something=document.getElementById('something');
something.onclick=function(){mouseclickfunc('mypassed','variables');}
something.onmouseover=function(){somefunc('some,thing');}
}
function mouseclickfunc(a,b){alert('First value is: '+a);alert('Second value is: '+a);}
function somefunc(a,b){alert('First value is: '+a);alert('Second value is: '+a);}
</script>
<div id="something">test</div>

Dal
07-22-2008, 01:41 AM
Thanks rangana but unfortunatly I need the events to be part of the html code. For example when I use the javascript function to apply css attributes the values are rewrote to the html.

<div id="something" style="Background-Color:#FFFFFF"></div>

document.getElementById('something').style.backgroundColor = "#000000" will result in;

<div id="something" style="Background-Color:#000000"></div>

Can it be done or do I have to use string search and replace on a html block code?

Thanks
Dal

rangana
07-22-2008, 01:46 AM
I'm confused (nothing new) :confused:

The code I've posted on post#2 translates to your goal:


<div id="something" onclick="mouseclickfunc(mypassed,variables);" onmouseover="somefunc(some,thing);">

jscheuer1
07-22-2008, 02:22 AM
I thought at first that this might be a quasi religious question (see recent posts for more explanation on that).

The DOM events of an element are a part of an element's properties.

Except when they are assigned via attachEvent or addEventListener.

I think that this is a huge hole in DOM level 2 that will be corrected at some time in the future.

So say you have:


<a id="example" onclick="alert(this.href);return false;" href="some.htm">whatever</a>

This will work (we are focusing our attention on the 'Check' button):


<!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 getEvent(id){
alert(document.getElementById(id).onclick);
}
</script>
</head>
<body>
<a id="example" onclick="alert(this.href);return false;" href="some.htm">whatever</a><br>
<input type="button" value="Check" onclick="getEvent('example');">
</body>
</html>

Or this:


<!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 getEvent(id){
alert(document.getElementById(id).onclick);
}
window.onload = function(){
document.getElementById('example').onclick = function(){
alert(this.href);return false;
}
}
</script>
</head>
<body>
<a id="example" href="some.htm">whatever</a><br>
<input type="button" value="Check" onclick="getEvent('example');">
</body>
</html>

But not this:


<!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 getEvent(id){
alert(document.getElementById(id).onclick);
}
function giveHref(e){
e = e? e : window.event;
var t = e.target? e.target : e.srcElement;
alert(t.href);
if (e.preventDefault)
e.preventDefault();
return false;
}
window.onload = function(){
if(typeof window.addEventListener!='undefined')
document.getElementById('example').addEventListener('click', giveHref, false);
else if(typeof window.attachEvent!='undefined')
document.getElementById('example').attachEvent('onclick', giveHref);
};
</script>
</head>
<body>
<a id="example" href="some.htm">whatever</a><br>
<input type="button" value="Check" onclick="getEvent('example');">
</body>
</html>

But the onclick event of the a tag will be identical in all three examples.

Dal
07-22-2008, 02:34 AM
I'm confused (nothing new) :confused:

The code I've posted on post#2 translates to your goal:


<div id="something" onclick="mouseclickfunc(mypassed,variables);" onmouseover="somefunc(some,thing);">


rangana : This is what I see when I look at the generated source code;



<html><head>

<script type="text/javascript">
window.onload=function()
{
var something=document.getElementById('something');
something.onclick=function(){mouseclickfunc('mypassed','variables');}
something.onmouseover=function(){somefunc('some,thing');}
}
function mouseclickfunc(a,b){alert('First value is: '+a);alert('Second value is: '+a);}
function somefunc(a,b){alert('First value is: '+a);alert('Second value is: '+a);}
</script>
</head><body>
<div id="something">test</div>
</body></html>


This is what I wanted though;



<html><head>

<script type="text/javascript">
window.onload=function()
{
var something=document.getElementById('something');
something.onclick=function(){mouseclickfunc('mypassed','variables');}
something.onmouseover=function(){somefunc('some,thing');}
}
function mouseclickfunc(a,b){alert('First value is: '+a);alert('Second value is: '+a);}
function somefunc(a,b){alert('First value is: '+a);alert('Second value is: '+a);}
</script>
</head><body>
<div id="something" onclick="mouseclickfunc(mypassed,variables);" onmouseover="somefunc(some,thing);">test</div>
</body></html>


jscheuer1, I think Im going to have to run the code you gave me there because I dont see what your point is... brb with my response on that one :D

Thanks
Dal

rangana
07-22-2008, 02:40 AM
Ah, I see your point Dal, but I don't think it's possible with JS. Remember that it's client-side. what you're after could be done, and will be made possible via server-side.

Hope that makes sense.

Dal
07-22-2008, 02:44 AM
jscheuer1: Uh? its not changing anything in the html element?

Is my question not explained enough. Think of it this way;

I want to modify this onclick function from

<div id="Anything" onclick="Oldfunction();"></div>

to;

<div id="Anything" onclick="Newfunction();"></div>

without rewitting the parent div. I need to access this part

<div id="Anything" onclick="Oldfunction();"></div>

via a DOM command. How do I address the document.getElementById('Anything') to access the string contained within the onclick="" param?

so If I wanted to change it to "ChickenDinner" I could simply write something like

document.getElementById('Anything').onclick.string("ChickenDinner") (<-- I obvously made this up but its more relative than what you guys seem to be aiming at)

I hope I made myself clear :)
Thanks
Dal

Dal
07-22-2008, 02:47 AM
Ah, I see your point Dal, but I don't think it's possible with JS. Remember that it's client-side. what you're after could be done, and will be made possible via server-side.

Hope that makes sense.

Im sure its possible just handles the same as any other DOM but I think you answered my question, its not been supported yet! :D

Thanks for your time. Sorry for the confussion. :confused: :)

Oh well, Ill handle the whole thing via PHP. Would have been a little neater if JS could have embedded and built its own code.

Cool
Thanks agian
Dal

rangana
07-22-2008, 02:55 AM
Oh, wait, try this:


<script type="text/javascript">
window.onload=function()
{document.getElementById('trig').onclick=function()
{
var prnt=document.getElementById('Anything');
prnt.removeAttribute('onclick');
prnt.onclick=function(){Newfunction();};
}
}
function Oldfunction()
{alert('This is the old function');}
function Newfunction()
{alert('This is the new function');}
</script>
<div id="Anything" onclick="Oldfunction();">
Contents
</div>
<input type="button" value="Change the function of Anything div to new" id="trig">

Dal
07-22-2008, 03:01 AM
Ahhh! soooo close.

I need something like removeAttribute maybe replaceAttribute or maybe removeAttribute then createAttribute?

Soo close my mouth is watering :D

:p

Kind regards
Dal

rangana
07-22-2008, 03:50 AM
So, the code I've recently shown does'nt meet your requirements? :confused:

Dal
07-22-2008, 03:58 AM
Oh, wait, try this:


<script type="text/javascript">
window.onload=function()
{document.getElementById('trig').onclick=function()
{
var prnt=document.getElementById('Anything');
prnt.removeAttribute('onclick');
prnt.onclick=function(){Newfunction();};
}
}
function Oldfunction()
{alert('This is the old function');}
function Newfunction()
{alert('This is the new function');}
</script>
<div id="Anything" onclick="Oldfunction();">
Contents
</div>
<input type="button" value="Change the function of Anything div to new" id="trig">


Hi rangana



<div id="Anything" onclick="Oldfunction();">
Contents
</div>


The code produces;


<div id="Anything">
Contents
</div>


I still need it to produce


<div id="Anything" onclick="Newfunction();">
Contents
</div>


Sorry, thats what I mean when I say "Ahhh! soooo close." ;)

Thanks
Dal

PS been messing about with createAttribute but it seems to only accept official DOM and not a string to fill the onclick"" param.

rangana
07-22-2008, 04:48 AM
I might be wrong, but that's impossible.

You cannot alter the code when the page has already loaded. Go server-side.

codeexploiter
07-22-2008, 05:10 AM
As you know one can mention the event handler in a number of different ways achieving the same results. In your case you mention the events and event handlers with the HTML tag itself, which I personally think used in old days. It will definitely offers user friendliness for some developers as they'll be able to identify the events associated with an HTML element quickly.

Now the developers tend to make clear distincation between the Markup (HTML), Presentation (CSS) and Behaviour (JavaScript) as a result most of the developers will opt for a JavaScript based method for attaching events to any HTML element(s).

Coming to your issue you have an HTML element like the following


<div id="srcDiv" onclick="oldFunction();"></div>

Now when the user clicks a button the above mentioned code should be changed to the following


<div id="srcDiv" onclick="newFunction();"></div>

This can be done using setAttribute() and it will definitely work in Mozilla Firefox but not in MS IE envioronment. In other word in IE one can't attach events dynamically to an HTML element using setAttribute(). You have to use other methods.

Here is one Demo



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled Document</title>
<style type="text/css">
#srcDiv{
width:100px;
height:100px;
border:1px solid blue;
background-color: gray;
}
</style>
<script type="text/javascript">
function oldFunction(){
alert('you are in old function');
}
function newFunction(){
alert('you are in new function');
}
function changeOldToNew(){
var srcDiv = document.getElementById('srcDiv');
srcDiv.setAttribute("onclick","newFunction();");
//srcDiv.onclick = newFunction;
//srcDiv["onclick"] = newFunction;
//srcDiv.onclick = function(){
newFunction();
}
}
</script>
</head>
<body>
<div id="srcDiv" onclick="oldFunction();"></div>
<form>
<input type="button" name="change" onclick="changeOldToNew();" value="change"/>
</form>
</body>
</html>


In the above code you can see that there 3 commented lines. All those 3 lines shows different ways of attaching events to HTML element dynamically that works in IE as well as FF.

The current method I've shown in the code is using the setAttribute() and this will work correctly in FF but not in IE though IE will definitely show the HTML element code as


<div id="srcDiv" onclick="newFunction();"></div>

* Please note that to view the generated HTML source you have to use tools like Firebug, Web Developer (add-ons) in Firefox and IE Developer Toolbar (in IE) where you can view the changes in the attribute of the HTML element.

Now you can comment the following line


srcDiv.setAttribute("onclick","newFunction();");

and uncomment any other commented line that does the event attaching and see its working.

Hope this helps.

Dal
07-22-2008, 05:26 AM
Wow codeexploiter! :o

Thats perfect!

Thanks alot :D

My reasons for keeping the old onclick="" catchment is that although the addEventListener/attachEvent is used in other parts of my script you hit the nail on the head with "It will definitely offers user friendliness for some developers as they'll be able to identify the events associated with an HTML element quickly." I also require this as the HTML generation is used elsewhere and is stored in a db for further minipulation without the other code which is redundant elsewhere. Why pickup all the functions which would apply the addEventListener/attachEvent to there parts when all I need is contained within the HTML block. Anyway that aside this works spot on and although I messed about with the setAttribute function I obvously didnt work it right.

Fantastic!
Thanks again for yours and everyone elses help. :D

Kind regards
Dal

jscheuer1
07-22-2008, 07:46 AM
I'm still a little confused as to what all this is about. If you want to change the onclick of an element, that is fairly straightforward and can be done at least two ways cross browser.

If the functions are both defined ahead of time, either will be available at any time for assignment/reassignment.

However, messing about with an element's events can have other consequences not intended, namely memory leaks.

If it is at all possible the entire appraoch shoud be rethought.

Let's say you have two functions:


function oldf(){
alert('I\'m old');
};
function newf(){
alert('I\'m new');
};

and two links:


<a id="theold" href="#" onclick="oldf();return false;">whatever</a>
<a style="display:none;" id="thenew" href="#" onclick="newf();return false;">whatever</a>

Now the user will only see the link with the id 'theold'. Say we want to make the change using a button:


<input type="button" value="Change" onclick="swap('theold', 'thenew');">


function swap(id1, id2){
document.getElementById(id1).style.display = document.getElementById(id1).style.display == 'none'? 'inline' : 'none';
document.getElementById(id2).style.display = document.getElementById(id2).style.display == 'none'? 'inline' : 'none';
}

In this manner, the two may be swapped whenever, and both the old and the new functions are preserved and always available. Nothing is assigned or removed, so there can be no memory issues. But from the user's point of view, what they see as the link, its onclick will change.

Here it is all put together:


<!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 oldf(){
alert('I\'m old');
};
function newf(){
alert('I\'m new');
};
function swap(id1, id2){
document.getElementById(id1).style.display = document.getElementById(id1).style.display == 'none'? 'inline' : 'none';
document.getElementById(id2).style.display = document.getElementById(id2).style.display == 'none'? 'inline' : 'none';
};
</script>
</head>
<body>
<a id="theold" href="#" onclick="oldf();return false;">whatever</a>
<a style="display:none;" id="thenew" href="#" onclick="newf();return false;">whatever</a><br>
<input type="button" value="Change" onclick="swap('theold', 'thenew');">
</body>
</html>

Dal
07-23-2008, 12:11 AM
Thanks jscheuer1 but I think codeexploiter is on the same wave length. I understand it isnt practicle to swap functions on elements for a page but what Im trying to get accross is this code is NOT for this page. I regroup the code insert new function calls on the onlcick event on a completetly different page on the site.

Page A
Div Element which contains a photo and when member clicks, opens up a dialogue to swap out the photo with something else.

Page B
Div Element which contains a photo and when user clicks, opens up the image as a preview (not swap-out)

If it was this simple then I could build a code based on that quite easily it just that there could potentially be hundreds of various functions that do all different kinds of things for the member but are handled differently when it is a general user.

Hope this explains it. Anyway, its solved now thanks to you and codeexploiter for your input.

However, I appreciate your concern on this issue but memory leaks cant happen as the page still sees the original code, this mod is for database storage so all new functions will be implanted before the page has passed onload as true.

:D
Thanks again
Dal