...

View Full Version : Attaching Javascript Functions On The Fly



knightcon
08-24-2008, 11:05 AM
I was wanting to know how I would go about attaching javascript functions to a html element on the fly such as...

Start HTML


<body>
<a href="sometext.html">test</a>
</body>


After Script Run


<body>
<a href="sometext.html" onclick="LinkClick('test', 'sometext.html')">test</a>
</body>

abduraooft
08-24-2008, 01:51 PM
<script type="text/javascript" >
window.onload=function(){
var mylink=document.getElementById('mylink');
mylink.onclick=function(){
LinkClick(this.innerHTML, this.href);
return false; // if not required to redirect to new page
}
}
function LinkClick(text,link){
alert(text+', '+ link);
}
</script>

<a href="sometext.html" id="mylink">test</a>

knightcon
08-24-2008, 11:59 PM
Thanks for that abduraooft. I was wanting to have it applied to all hyperlinks on a page but there is no reason why i cant alter the code you have supplied to loop through the page and apply the code to all <a> elements and in fact any element on the page I would like to apply changes to.

Thanks again.

abduraooft
08-25-2008, 09:15 AM
window.onload=function(){
var mylinks=document.getElementById('mydiv').getElementsByTagName('a');
for(var i=0;i<mylinks.length;i++)
mylinks[i].onclick=function(){
LinkClick(this.innerHTML, this.href);
return false; // if not required to redirect to new page
}
}

<div id="mydiv">
<a href="sometext1.html" >test1</a>
<a href="sometext2.html" >test2</a>
<a href="sometext3.html" >test3</a>
<a href="sometext4.html" >test4</a>
</div>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum