Possible Duplicate:
The current element as its Event function param
Would this work
<script type="text/javascript"> var foo = function(param) { param.innerHTML = "Not a button"; }; </script> <button onclick="foo(this)" id="bar">Button</button>
rather than this?
<script type="text/javascript"> var foo = function() { document.getElementId("bar").innerHTML = "Not a button"; }; </script> <button onclick="foo()" id="bar">Button</button>
And would the first method allow me to load the javascript from elsewhere to perform actions on any page element?
Why is the onclick event triggered twice? 1 Answers. It is calling twice because button is inside a span and span has onclick="alert('Boem')" , hence when you trigger click on button then it shows alert and same click event propagate to span and shows alert once again.
As you can see, the this keyword is present in the onclick method. Therefore it refers to the HTML element. But if you do <element onclick="doSomething()"> alert(element.onclick) you get function onclick() { doSomething() } This is merely a reference to function doSomething() .
Yes, you can call two JS Function on one onClick. Use semicolon (';') between both the functions.
The first solution to perform multiple onClick events in React is to include all of your actions inside of a function and then call that single function from the onClick event handler. Let's explore how to do that in a React Component: import React from 'react'; function App() { function greeting() { console.
The code that you have would work, but is executed from the global context, which means that this
refers to the global object.
<script type="text/javascript"> var foo = function(param) { param.innerHTML = "Not a button"; }; </script> <button onclick="foo(this)" id="bar">Button</button>
You can also use the non-inline alternative, which attached to and executed from the specific element context which allows you to access the element from this
.
<script type="text/javascript"> document.getElementById('bar').onclick = function() { this.innerHTML = "Not a button"; }; </script> <button id="bar">Button</button>
You can always call funciton differently: foo.call(this);
in this way you will be able to use this
context inside the function.
Example:
<button onclick="foo.call(this)" id="bar">Button</button>
var foo = function() { this.innerHTML = "Not a button"; };
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