Alfra
Alfra

Reputation: 165

Disable href and execute function

I have this code:

<a href="link.cshtml">
    <div>...</div>
    <div class="function">...</div>
    <div>....</div>
</a>

I would like disable href on div with class function and call a function when I click on this div.

I have tried with onclick="return false; testFunction();" but obviously it doesn't work.

Can someone help me?

Thanks in advance

Upvotes: 2

Views: 279

Answers (4)

user8278502
user8278502

Reputation:

you can do this :

$('#content a').click(function(){ return false });

Returning false from the click event handler prevents the default behavior (following the link).

If you may have more than one link but you want to disable only this one, you may be more specific in your selector :

$('#content a[href="/test/"]').click(function(){ return false });

Upvotes: 0

mrJ0ul3
mrJ0ul3

Reputation: 126

$('#selector').on('click', function(e) {
  e.preventDefault();
  alert("Cool!");
});

Upvotes: 0

SilverSurfer
SilverSurfer

Reputation: 4368

Another way to make it is with javascript:void(0) and click event via jquery

$(".function").click(function(){
 console.log("test")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:void(0)">
    <div>...</div>
    <div class="function">Click here will not change page</div>
    <div>....</div>
</a>

Upvotes: 0

Dekel
Dekel

Reputation: 62556

  1. You should use the preventDefault to make sure the browser will not run the default href.
  2. If you return - nothing will run after that...

function testFunction() {
  alert('hi');
}
document.querySelector('.function').addEventListener('click', function() {
  event.preventDefault();
  testFunction();
});
<a href="https://www.yahoo.com">
    <div>...</div>
    <div class="function">Click here will not change page</div>
    <div>....</div>
</a>

Upvotes: 3

Related Questions