Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop an anchor from redirecting using JQuery

Tags:

How can I stop an anchor tag redirecting to another page if the user is not logged in? I have a function to check if the user is logged in or not. I want to do it with JQuery or JavaScript. Here is what I have tried so far but with no results:

<a href="www.somewhere.com" id="yes">Read More</a>  <script type="text/javascript">     $(document).ready(function(){         $('a').click(function(){             var id = $(this).attr('id');             if(id == 'yes'){                 //i want to prevent             }else{                 //redirect             }         });     }); </script> 
like image 817
Ankit Avatar asked Jun 28 '12 08:06

Ankit


People also ask

How do I stop a link from redirecting in jQuery?

The jQuery's one of the most useful method — event. preventDefault() , it stops the default action of an element from happening. event. preventDefault();

How do you stop a href from redirecting?

From the drop-down menu select Settings then scroll down and click Advanced. In the Privacy & security section choose Content settings > Pop-ups and redirects then ensure that the Allowed option is turned off.

How do I stop JavaScript from redirecting?

In that case, the new page can use JavaScript to redirect our article to a phishing page asking for BleepingComputer credentials. To prevent this from happening, a rel="noopener" HTML link attribute was created that prevents a new tab from using JavaScript to redirect the page.


1 Answers

Please use http://api.jquery.com/event.preventDefault/

demo http://jsfiddle.net/aRBY4/6/

e.preventDefault()  

quote

If this method is called, the default action of the event will not be triggered.

Also if I may suggest read this: .prop() vs .attr()

Hope this helps,

sample code

  $('a').click(function(event){     event.preventDefault();     //do whatever   }); 

In your case please try this

$(document).ready(function() {     $('a').click(function(event) {         var id = $(this).attr('id');         if (id == 'yes') {             event.preventDefault();             //i want to prevent         } else {             //redirect         }     }); });​ 
like image 91
Tats_innit Avatar answered Sep 19 '22 17:09

Tats_innit