Henrik Petterson
Henrik Petterson

Reputation: 7094

Stop <a> tag from loading href value

I have something like this:

<a href="http://example.com">
   <span>text</span>
   <button class="hello">hello</button>
</a>

When user clicks the <button> I don't want the page to go to the href value of the parent <a> tag. Is there any way to stop it from redirecting without moving the button outside of the anchor tag?

So hooking into the button:

jQuery( document ).on( 'click', '.hello', function() {
    // STOP redirect
});

What's the solution?

Upvotes: 1

Views: 327

Answers (5)

juan garcia
juan garcia

Reputation: 1516

So you can do this:

<a href="www.example.com">
   <span>text</span>
   <button class="hello" id="btnhello">hello</button>
</a>

And then

$('#btnhello').onclick((ev) => {
  ev.preventDefault();
  ev.stopPropagation();
});

You have the button to call event prevent default so it does not do a submit default behaviour by many browsers, and the event stopPropagation allows not to propagate the event to the parent, the anchor when you click on the button.

Upvotes: 1

Nikita Vozisov
Nikita Vozisov

Reputation: 66

Yes, you can use preventdefault - it prevents standard behavior or you can return false in click function

<a href="/" onclick="return false">Press </a>
     or 
<a href="/" onclick="event.preventDefault()">Press </a>

Upvotes: 0

Confuser
Confuser

Reputation: 71

have you tried this code?

window.jQuery('.hello').click(function(event){ event.preventDefault(); alert("YaY!"); });

Upvotes: 1

Sachin Bankar
Sachin Bankar

Reputation: 382

ruturn false would stopt it from redirecting it to any other page :

jQuery( document ).on( 'click', '.hello', function() {
    // your Code goes here
    // STOP redirect
    return false;
});

Upvotes: 0

Eddie
Eddie

Reputation: 26844

You can use e.preventDefault(); to prevent the page on going to href URL.

jQuery(document).on('click', '.hello', function(e) {
  e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="http://example.com">
  <span>text</span>
  <button class="hello">hello</button>
</a>

Doc: https://api.jquery.com/event.preventdefault/

Upvotes: 5

Related Questions