Javascript onclick function is called immediately (not when clicked)?
You want .onclick = secondFunction
NOT .onclick = secondFunction()
The latter calls (executes) secondFunction
whereas the former passes a reference to the secondFunction
to be called upon the onclick
event
function start() { var a = document.createElement("a"); a.setAttribute("href", "#"); a.onclick = secondFunction; a.appendChild(document.createTextNode("click me")); document.body.appendChild(a);}
function secondFunction() { window.alert("hello!");}
start();
OnClick events created through JavaScript are triggering immediately, not when the object is clicked
You're calling MyFunction
, not assigning it as the event handler, because you're including the brackets. Change the line to
object1.onclick=myFunction;
onClick event on a button fires even if the button is not clicked
I see 2 major issues:
onClick
should beonclick
;logInToPod()
should belogInToPod
.
So I would suggest to modify your code like:
window.onload = function(){
document.getElementById('loginButton').onclick = logInToPod;
}
Here a JSFiddle example.
Script doesn't wait for onclick event
The issue is this line:
button1.onclick = change_text("header", "something")
The JS engine will do the following in this order:
- Call
change_text
with the arguments"header"
and"something"
- Assign the result of
change_text
(in this case,undefined
) tobutton1.onclick
Jane Doe's answer should work. If you want to keep your current code structure, then you could use the following:
button1.onclick = function(){
change_text("header", "something");
};
This creates an anonymous function and assigns it to onclick
. When onclick
is triggered, it will execute the function which calls change_text
.
why click event is fired first called by onclick on element, rather than $(document).on('click')?
onclick attr will be called first because its direct event on the element
this is how it is but you can make some manipulations on the events from the function itself
here is a way you can achieve what you want but as I said in my comment is a bit messy:
<!DOCTYPE HTML>
<html ng-app>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<a id="click" onclick="show(this);">c</a>
<script type="text/javascript">
function show(t){
events = $._data(document, 'events');
events.click[0].handler();
alert("hi");
$(document).off("click","#click");
}
$(document).on("click","#click",function(){
alert("bye");
});
</script>
</body>
</html>
basicly what you do here is to call other handlers before you execute your onclick function logic on in other words you call other handlers from the onclick this code works but you should use some filters for the events you are looking for and run in a loop on each event
another way you can do it you can save the onclick value and attached it in the your own event and then remove the onclick attr val:
http://jsfiddle.net/qmbcgz5y/11/
function add(){
alert("add");
}
function sub(){
alert("sub");
}
function div(){
alert("div");
}
function firstfunction(){alert('first func');}
$(function(){
$("input[type=button]").each(function(){
var onclickfunc = $(this).attr('onclick');
$(this).attr('onclick','');
$(this).on('click',function(){
firstfunction();
eval(onclickfunc);
});
});
});
Calling a javascript function on button onclick
encode.onclick()
tries to call onclick
immediately. This gives you a value. (Or it throws an exception because it is undefined
instead of a function you can call).
=Encode();
then calls Encode
immediately and tries to assign its return value to the LHS. Since the LFS is a value (and not a property or a variable), this throws an error.
The correct (albeit ancient) syntax would be encode.onclick = Encode
.
The modern approach is addEventListener
. Stick to that.
Onclick calling functions diffrences
In the original post, there's already a post on function() vs function.
In summary (and in layman terms), though, there are 2 ways on how you handle onClick.
When you want to pass some value to the function
//the button
<button onClick={() => myFunction('I am a click')}>Button</button>
//the function
const myFunction = (value) => {
console.log(value) //prints 'I am a click'
}
When you do NOT need to pass any value (events/default props will be passed by default)
//the button
<button onClick={myEvent}>Button</button>
//the function
const myFunction = (event) => {
console.log(event) //prints the button element
}
Creating a custom Button component with custom props.
const MyButton = ({ onClick }) => {
const customOnClick = () => {
onClick('Somebody', 'Special'); //we call the onclick here
}
return <button onClick={customOnClick}>Click Me</button>
}
const App =() => {
//the onClick in MyButton component actually triggers this function.
const onClick = (value, value2) => {
console.log(value,value2) //prints "Somebody Special"
}
return (<MyButton onClick={onClick} />) // i do not need to specify the props to pass
}
Related Topics
What Is the Most Efficient Way to Deep Clone an Object in JavaScript
Why Does Date.Parse Give Incorrect Results
How to Format a Date in JavaScript
Why Is Using "For...In" For Array Iteration a Bad Idea
Is JavaScript a Pass-By-Reference or Pass-By-Value Language
Which Equals Operator (== VS ===) Should Be Used in JavaScript Comparisons
How to Convert an Existing Callback API to Promises
JavaScript Property Access: Dot Notation Vs. Brackets
Var Functionname = Function() {} VS Function Functionname() {}
Xmlhttprequest Cannot Load Xxx No 'Access-Control-Allow-Origin' Header
Ways to Circumvent the Same-Origin Policy
"Thinking in Angularjs" If I Have a Jquery Background
How to Randomize (Shuffle) a JavaScript Array
How to Upload Files Asynchronously With Jquery
Use a Content Script to Access the Page Context Variables and Functions