Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    Apr 2007
    Location
    Griffith. Australia
    Posts
    138
    Thanks
    4
    Thanked 4 Times in 4 Posts

    Attaching Javascript Functions On The Fly

    I was wanting to know how I would go about attaching javascript functions to a html element on the fly such as...

    Start HTML
    Code:
    <body>
    <a href="sometext.html">test</a>
    </body>
    After Script Run
    Code:
    <body>
    <a href="sometext.html" onclick="LinkClick('test', 'sometext.html')">test</a>
    </body>

  • #2
    Supreme Master coder! abduraooft's Avatar
    Join Date
    Mar 2007
    Location
    N/A
    Posts
    14,866
    Thanks
    160
    Thanked 2,224 Times in 2,211 Posts
    Code:
    <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>
    Code:
    <a href="sometext.html" id="mylink">test</a>
    The Dream is not what you see in sleep; Dream is the thing which doesn't let you sleep. --(Dr. APJ. Abdul Kalam)

  • #3
    Regular Coder
    Join Date
    Apr 2007
    Location
    Griffith. Australia
    Posts
    138
    Thanks
    4
    Thanked 4 Times in 4 Posts
    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.

  • #4
    Supreme Master coder! abduraooft's Avatar
    Join Date
    Mar 2007
    Location
    N/A
    Posts
    14,866
    Thanks
    160
    Thanked 2,224 Times in 2,211 Posts
    Code:
    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
     }
    }
    Code:
    <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>
    The Dream is not what you see in sleep; Dream is the thing which doesn't let you sleep. --(Dr. APJ. Abdul Kalam)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •