Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inline javascript onclick event

Tags:

javascript

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.

like image 798
Vicky Avatar asked Jul 19 '12 19:07

Vicky


People also ask

How to add inline onClick event in JavaScript?

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.

How do you write an inline function in JavaScript?

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.

What is onClick JavaScript?

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.

Can we use onClick in anchor tag?

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.


1 Answers

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();
}
like image 170
Trolzie Avatar answered Sep 17 '22 15:09

Trolzie