Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing 'this' to an onclick event [duplicate]

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?

like image 562
FatalKeystroke Avatar asked Oct 10 '12 06:10

FatalKeystroke


People also ask

Why is Onclick called twice?

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.

What does this refer to in Onclick?

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() .

Can Onclick have two functions?

Yes, you can call two JS Function on one onClick. Use semicolon (';') between both the functions.

Can we pass two functions onclick event react?

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.


2 Answers

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> 
like image 148
Konstantin Dinev Avatar answered Sep 24 '22 06:09

Konstantin Dinev


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"; }; 
like image 30
Arkadiusz 'flies' Rzadkowolski Avatar answered Sep 24 '22 06:09

Arkadiusz 'flies' Rzadkowolski