How to Prevent Default Event Handling in an Onclick Method

How to prevent default event handling in an onclick method?

Let your callback return false and pass that on to the onclick handler:

<a href="#" onclick="return callmymethod(24)">Call</a>

function callmymethod(myVal){
//doing custom things with myVal
//here I want to prevent default
return false;
}

To create maintainable code, however, you should abstain from using "inline Javascript" (i.e.: code that's directly within an element's tag) and modify an element's behavior via an included Javascript source file (it's called unobtrusive Javascript).

The mark-up:

<a href="#" id="myAnchor">Call</a>

The code (separate file):

// Code example using Prototype JS API
$('myAnchor').observe('click', function(event) {
Event.stop(event); // suppress default click behavior, cancel the event
/* your onclick code goes here */
});

How to prevent default on a button click

You need to add the event parameter to the CollectData and prevent default action like you do in the first case:

<div class="EMail_Pwd_JoinPage"><button class="btn_joinnow" style="color:rgb(255,255,255);" id="btn_submit"
onclick="GetDate(); GetCkBx(); CollectData(event);">Submit Information</button></div>

function CollectData(event) {
event.preventDefault();
.........

Ignore prevent default with an onclick function

Just read the URL from the link being clicked (the element which triggers the event is available as e.target in your listener):

var link = document.getElementById('view-cart');
// let's assume some Javascript has added a listener which does preventDefault()// so now clicking it does nothing (the following 3 lines simulate that)link.addEventListener('click', (e) => { e.preventDefault()})
// now let's console.log the href of the link on clicklink.addEventListener('click', function(e) { console.log(e.target.href); // you wanna do this here: // window.location.href = e.target.href})
<p id="addToCartMessage"><span class="text-success">Products successfully added to cart! <a href="http://webshop.local/cart/" title="cart" class="notification-cart-link" id="view-cart">View cart</a></span></p>

Access event to call preventdefault from custom function originating from onclick attribute of tag

I believe you can pass in event into the function inline which will be the event object for the raised event in W3C compliant browsers (i.e. older versions of IE will still require detection inside of your event handler function to look at window.event).

A quick example.

function sayHi(e) {   e.preventDefault();   alert("hi");}
<a href="http://google.co.uk" onclick="sayHi(event);">Click to say Hi</a>

jQuery preventDefault() stops onclick from working

As adeneo and Jeremy have mentioned, do not use inline event handlers. They will interfer with your jQuery event handler.

Simply merge the 2 functions into one, and it will work:

$("#main a").bind("click", function (e) { 
e.preventDefault();

var p = $(this).position();
$("#loader").css("top", p.top - 20);
$("#loader").toggle();
});

JSFiddle


If I put the function inside my function it works. But I want to have different onclick functions on the links.

If you want to have different onclick functions on different links, then use classes (or IDs) and select them appropriately with jQuery.

HTML:

<div id="main">
<p><a class="doSomething" href="#">I will NOT JUMP!</a></p>
<p><a class="doSomethingElse" href="#">I will NOT JUMP</a></p>
</div>

jQuery:

$("#main a.doSomething").bind("click", function (e) { 
e.preventDefault();

var p = $(this).position();
$("#loader").css("top", p.top - 20);
$("#loader").toggle();
});

$("#main a.doSomethingElse").bind("click", function (e) {
e.preventDefault();

//Other code
});

JSFiddle demo

Javascript prevent default onclick in code

Put it as a parameter in your on click handler

document.getElementById('elementId').onclick = function(event){    
event.preventDefault()
}

jQuery preventDefault onclick function

You need to remove original onclick and give it back in this case because you can't influent on onclick handler.

const btn = $(".mybutton");const onclick = btn.prop('onclick'); // save onclick fn
btn.prop('onclick', null); // remove onclick from buttonbtn.one('click', function() { $(this).html("Are you sure?"); btn.on('click', onclick); // add onclick back to button});
function test() { $(".forthebutton").html("button click function worked"); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="mybutton" onclick="test();">Button</button>
<br /><br /><br />
<span class="forthebutton">button click should change this text</span>

React onClick and preventDefault() link refresh/redirect?

React events are actually Synthetic Events, not Native Events. As it is written here:

Event delegation: React doesn't actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React's event handlers are simple no-ops.

Try to use Use Event.stopImmediatePropagation:

upvote: (e) ->
e.stopPropagation();
e.nativeEvent.stopImmediatePropagation();

How to use event.preventDefault() when function have arguments

modify your onclick like so

<button onClick = {(e) => upListCandy(item,e)}>{item.name}</button>

and then

const upListCandy = (candy,event) => {
event.preventDefault();
axios.post("example.com", {
candyName: candy.name
}).then().catch()
}


Related Topics



Leave a reply



Submit