Alive Nick
Alive Nick

Reputation: 23

Apply A Function to All Links on Page

i have my all links on page like this :

<a href="http://example.com">Example</a>

But Now I Want All Links With Following OnClick Function like this:

<a onclick="show();" href="http://example.com">Example</a>

can any one tell me jquery or javascript code to add above function to all links on body, thanks

Upvotes: 2

Views: 223

Answers (3)

Liftoff
Liftoff

Reputation: 25412

$(function(){

    $("a").click(function(){
        show();
    }
});

If you want to prevent the browser from following the href, you can just add a preventDefault call

$(function(){
    $("a").click(function(e){
        e.preventDefault();
        show();
    }
});

Note that this will not actually append the onclick= to the <a> tags. If you want to do that, you can do it this way:

$("a").each(function(){
    $(this).attr("onclick", $(this).attr("onclick")+";show();");
});

Upvotes: 1

Nicklas Nygren
Nicklas Nygren

Reputation: 2605

Some answers have suggested to use jQuery's click() function. That's alright as long as you don't expect to add new links dynamically using javascript.

This click handler will bind on the <body> element, and fire whenever a <a> element inside it is clicked. The advantage with this over $('a').click(...) is that all <a> tags don't need to be present on page load:

$(function () {
  $('body').on('click', 'a', function (event) {
    event.preventDefault();
    show();
  });
});

Fiddle: http://jsfiddle.net/Lubf6gjw/2/

EDIT: Here's how to do it with pure javascript:

document.querySelector('body')
.addEventListener('click', function (event) {
    if(event.target.tagName === 'A') { 
        event.preventDefault();
        show();
    }
});

http://jsfiddle.net/pymwsgke/1/

Upvotes: 1

Gildas.Tambo
Gildas.Tambo

Reputation: 22663

Using pure Js

 function show (event) {
   event.preventDefault();
  // do somethink
}
var anchors = document.querySelectorAll("a");
for(var a = 0; a < anchors.length; a++) {
     anchors[a].addEventListener("click",show,false)
}

Upvotes: 0

Related Questions