Anwar
Anwar

Reputation: 51

How to prevent default action for an Anchor tag using Javascript?

I'm trying to prevent default action on an anchor ("a") tag. In my scenario few lines of html are rendered on the fly using ajax (after a form is submitted) and I want to add an event listener that

  1. performs an action when a newly created link is clicked

  2. prevent the browser from opening that link.

Here's what I'm writing:

a = document.getElementById("new_link");
a.addEventListener("click",function(){alert("preform action");
                                      return false;},false);

I have also tried:

a.addEventListener("click",function(e){e.preventDefault(); alert("preform action");});

When I click on the link "a" it shows the alert message but still opens the "href" link where as I want it to show the message and then stop.

Both methods show alerts if attached to an pre-existing link but do not work when attached to newly inserted links (via ajax).. which is what I need to do.

Any help/suggestions.

Thanks.

Upvotes: 5

Views: 32716

Answers (6)

Rukshan C
Rukshan C

Reputation: 43

You can do this by adding "event.preventDefault();" as 'onclick' value on your anchor tag

for example:-

<a href="#" onclick="event.preventDefault()">Text goes here</a>

Upvotes: -1

Siv
Siv

Reputation: 1066

Simple Way

Also There is a Simple way to do this

that is by returning Boolean values..

example :

 <a href='#link' onClick='return false;' > Prevent Link </a>;

Using jquery to make it bit more interesting

$('a').click(function (){

   //or if you want to perform some conditions    
   if(condition){
     // your script
   }

   return false;
});

Hope it helps ☻

Upvotes: 1

Siv
Siv

Reputation: 1066

simply you can do this by adding "javascript:void(0);" as your 'href' value

for example :-

<a href="javascript:void(0)" > some link </a>

or you can achive this using jQuery

$('link-identifier').attr("href", "javascript:void(0);");

Upvotes: 3

Jason Hazel
Jason Hazel

Reputation: 141

Reviving an old topic, but I wanted to provide an option that didn't rely on jQuery.

a = document.getElementById("new_link");
a.addEventListener("click",function(){
     alert("preform action");
     window.event.preventDefault();
},false);

Upvotes: 6

caseyohara
caseyohara

Reputation: 83

Using the jQuery library, you can stop the event which was bound to the jQ object (in this case, all elements) by calling the .preventDefault() method on the event passed as a parameter of the callback.

Try this:

$('a').click( function(e) {
  e.preventDefault();
  alert("perform action");
});

Upvotes: 5

konus
konus

Reputation: 1612

You could use the idea behind the jquery-nolink plugin and do something like this:

$('new_link').attr("href", "javascript:void(0);");

Upvotes: 3

Related Questions