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>
The jQuery's one of the most useful method — event. preventDefault() , it stops the default action of an element from happening. event. preventDefault();
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.
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.
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 } }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With