This is my html code
<a href="#" onclick="return clickHandler()">Hit</a>
This is my javascript file
function clickHandler(evt) {
var thisLink = (evt)?evt.target:Window.event.srcElement;
alert(thisLink.innerHTML);
return false;
}
But when i click the Hit Link, it redirects.
Declare it once. If you need to associate certain data with the <a> , use a data-* attribute and render information there. And don't set the onclick in the tag - wait for the DOM to be ready, get all <a> elements, and bind a click handler to each, calling doSomething and passing it the data-* attribute you may need.
var func = function() { //Your Code Here }; Explanation: Making an inline function is really simple. First, make an anonymous function(a function with no name), and then assign it to a variable.
The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form, when you change certain content on the web page, and other things like that. You place the JavaScript function you want to execute inside the opening tag of the button.
It is safe to click on that link with # href; the page does leave/reload url. Follow the above advice with caution, as HTML5 rules explicitly state that href="#" is supposed to navigate to the top of the page. You can simply add the href attibute without content, and get the click behaviour.
you need to pass in the event if you wish to preventDefault.
html:
<a href="#" onclick="runFunction(event)">Hit</a>
script:
function runFunction (evt) {
evt.preventDefault();
evt.stopPropagation();
}
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