How Can I add the an onload to ever href automatically?

Discussion in 'JavaScript' started by yyyk9, Sep 6, 2008.

  1. #1
    I want to add
    onClick="javascript:count()" within each href on a page
    automatically, how can I do it?
     
    yyyk9, Sep 6, 2008 IP
  2. Vooler

    Vooler Well-Known Member

    Messages:
    1,146
    Likes Received:
    64
    Best Answers:
    4
    Trophy Points:
    150
    #2
    Not a problem, following works in IE and FireFox, I tested before posting.

    
    function captureLinks() {
    	var nF = document.getElementsByTagName('a');
    	for(var i=0; i<nF.length; i++) 
    		nF[i].href = "javacript:count();";
    
    }
    Code (markup):
    regards
     
    Vooler, Sep 7, 2008 IP
  3. zerxer

    zerxer Peon

    Messages:
    368
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #3
    He wants to set it to the onclick event, not the href. You can use same code just change the .href line to like nF.onclick = "function(){count();}" I'd think it'd be.

    I'd honestly recommend checking out jQuery. It'd be a lot easier to do things like that. With it, you'd just do..

    <script type="text/javascript">
    $(function(){
      $("a").click(function(){
        count();
      });
    });
    </script>
    HTML:
    The $(function(){}) part binds a function to the ready event for the entire document, $("a").click(function(){}) binds a function to every "a" tag in the body, and then you'd just make it call the count() function inside that binded function.
     
    zerxer, Sep 10, 2008 IP