document.querySelector(DOM.refreshRem).addEventListener('click', function(param));
This is the line I'm having trouble with, I want to connect the function but without the (), so it isn't invoked right away, but the function accepts a parameter, so how do I go around it, my first idea would be to just wrap it in another function, but is there an easier way, this seems like too much nesting
So use a function or use bind
function test1(event, param) {
console.log(param)
}
function test2(param, event) {
console.log(param)
}
const btn1 = document.querySelector('.test1')
btn1.addEventListener('click', function(event) {
test1(event, 'foo')
});
const btn2 = document.querySelector('.test2')
btn2.addEventListener('click', test2.bind(btn2, 'bar'));
<button type="button" class="test1">click 1</button>
<button type="button" class="test2">click 2</button>
Related
Is there any way to use the onclick html attribute to call more than one JavaScript function?
onclick="doSomething();doSomethingElse();"
But really, you're better off not using onclick at all and attaching the event handler to the DOM node through your Javascript code. This is known as unobtrusive javascript.
A link with 1 function defined
Click me To fire some functions
Firing multiple functions from someFunc()
function someFunc() {
showAlert();
validate();
anotherFunction();
YetAnotherFunction();
}
This is the code required if you're using only JavaScript and not jQuery
var el = document.getElementById("id");
el.addEventListener("click", function(){alert("click1 triggered")}, false);
el.addEventListener("click", function(){alert("click2 triggered")}, false);
I would use the element.addEventListener method to link it to a function. From that function you can call multiple functions.
The advantage I see in binding an event to a single function and then calling multiple functions is that you can perform some error checking, have some if else statements so that some functions only get called if certain criteria are met.
Sure, simply bind multiple listeners to it.
Short cutting with jQuery
$("#id").bind("click", function() {
alert("Event 1");
});
$(".foo").bind("click", function() {
alert("Foo class");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo" id="id">Click</div>
ES6 React
<MenuItem
onClick={() => {
this.props.toggleTheme();
this.handleMenuClose();
}}
>
var btn = document.querySelector('#twofuns');
btn.addEventListener('click',method1);
btn.addEventListener('click',method2);
function method2(){
console.log("Method 2");
}
function method1(){
console.log("Method 1");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Pramod Kharade-Javascript</title>
</head>
<body>
<button id="twofuns">Click Me!</button>
</body>
</html>
You can achieve/call one event with one or more methods.
You can add multiple only by code even if you have the second onclick atribute in the html it gets ignored, and click2 triggered never gets printed, you could add one on action the mousedown but that is just an workaround.
So the best to do is add them by code as in:
var element = document.getElementById("multiple_onclicks");
element.addEventListener("click", function(){console.log("click3 triggered")}, false);
element.addEventListener("click", function(){console.log("click4 triggered")}, false);
<button id="multiple_onclicks" onclick='console.log("click1 triggered");' onclick='console.log("click2 triggered");' onmousedown='console.log("click mousedown triggered");' > Click me</button>
You need to take care as the events can pile up, and if you would add many events you can loose count of the order they are ran.
One addition, for maintainable JavaScript is using a named function.
This is the example of the anonymous function:
var el = document.getElementById('id');
// example using an anonymous function (not recommended):
el.addEventListener('click', function() { alert('hello world'); });
el.addEventListener('click', function() { alert('another event') });
But imagine you have a couple of them attached to that same element and want to remove one of them. It is not possible to remove a single anonymous function from that event listener.
Instead, you can use named functions:
var el = document.getElementById('id');
// create named functions:
function alertFirst() { alert('hello world'); };
function alertSecond() { alert('hello world'); };
// assign functions to the event listeners (recommended):
el.addEventListener('click', alertFirst);
el.addEventListener('click', alertSecond);
// then you could remove either one of the functions using:
el.removeEventListener('click', alertFirst);
This also keeps your code a lot easier to read and maintain. Especially if your function is larger.
React Functional components
<Button
onClick={() => {
cancelAppointment();
handlerModal();
}}
>
Cancel
</Button>
const callDouble = () =>{
increaseHandler();
addToBasket();
}
<button onClick={callDouble} > Click </button>
It's worked for me, you can call multiple functions in a single function. then call that single function.
Here is another answer that attaches the click event to the DOM node in a .js file. It has a function, callAll, that is used to call each function:
const btn = document.querySelector('.btn');
const callAll =
(...fns) =>
(...args) =>
fns.forEach(fn => fn?.(...args));
function logHello() {
console.log('hello');
}
function logBye() {
console.log('bye');
}
btn.addEventListener('click',
callAll(logHello, logBye)
);
<button type="button" class="btn">
Click me
</button>
You can compose all the functions into one and call them.Libraries like Ramdajs has a function to compose multiple functions into one.
Click me To fire some functions
or you can put the composition as a seperate function in js file and call it
const newFunction = R.compose(fn1,fn2,fn3);
Click me To fire some functions
This is alternative of brad anser - you can use comma as follows
onclick="funA(), funB(), ..."
however is better to NOT use this approach - for small projects you can use onclick only in case of one function calling (more: updated unobtrusive javascript).
function funA() {
console.log('A');
}
function funB(clickedElement) {
console.log('B: ' + clickedElement.innerText);
}
function funC(cilckEvent) {
console.log('C: ' + cilckEvent.timeStamp);
}
div {cursor:pointer}
<div onclick="funA(), funB(this), funC(event)">Click me</div>
I am using the ButtonGroup and Button from ReactStrap. I have set an onClick function when you click one of the buttons:
< ButtonGroup >
<Button>Edit</Button>
<Button onClick={console.log("Print some text")}>Print text</Button>
<Button>Set as default</Button>
</ButtonGroup >
But when I load the page this is what I get:
Before I have even clicked the button. And if I do click it, nothing comes out in the console. Any ideas?
Onclick must be function. You just set onlick as result of console.log("Print some text")
Try this
<Button onClick={() => {console.log("Print some text")}}>Print text</Button>
onClick parameter is evaluated as a callback, so if you pass something that is not a function, is evaluated and executed in the runtime.
Instead, you should pass a function to the onClick parameter:
<Button onClick={() => { console.log("Print some text"); }}>Print text</Button>
Be careful with the inline functions because they are evaluated each time that render is executed, that can be multiple times, each functions is more memory used by the browser.
If you has a class, you can use a arrow fat method:
/* ... */
handleOnClick = () => {
console.log("Print some text");
}
render() {
return (
<ButtonGroup>
<Button>Edit</Button>
<Button onClick={this.handleOnClick}>Print text</Button>
<Button>Set as default</Button>
</ButtonGroup >
);
}
/* ... */
To make it clearer
On any event trigger (onClick, onChange , etc) you must specified a function to call when the event occur
not calling the function right away
Consider this function
ES5:
function callMe() {
console.log("Some text");
}
ES6:
const callMe = () => {
console.log("Some text");
}
if you want to call this function when clicking the button you can't do this
<Button onClick={callMe()}>Print text</Button>
This will call the fuction callMe when the button is loaded once.
What you need to do to make it works is
<Button onClick={callMe}>Print text</Button>
Notice that there is no parenthesis after the function name which indicate that the function is not yet called.
I am using the ButtonGroup and Button from ReactStrap. I have set an onClick function when you click one of the buttons:
< ButtonGroup >
<Button>Edit</Button>
<Button onClick={console.log("Print some text")}>Print text</Button>
<Button>Set as default</Button>
</ButtonGroup >
But when I load the page this is what I get:
Before I have even clicked the button. And if I do click it, nothing comes out in the console. Any ideas?
Onclick must be function. You just set onlick as result of console.log("Print some text")
Try this
<Button onClick={() => {console.log("Print some text")}}>Print text</Button>
onClick parameter is evaluated as a callback, so if you pass something that is not a function, is evaluated and executed in the runtime.
Instead, you should pass a function to the onClick parameter:
<Button onClick={() => { console.log("Print some text"); }}>Print text</Button>
Be careful with the inline functions because they are evaluated each time that render is executed, that can be multiple times, each functions is more memory used by the browser.
If you has a class, you can use a arrow fat method:
/* ... */
handleOnClick = () => {
console.log("Print some text");
}
render() {
return (
<ButtonGroup>
<Button>Edit</Button>
<Button onClick={this.handleOnClick}>Print text</Button>
<Button>Set as default</Button>
</ButtonGroup >
);
}
/* ... */
To make it clearer
On any event trigger (onClick, onChange , etc) you must specified a function to call when the event occur
not calling the function right away
Consider this function
ES5:
function callMe() {
console.log("Some text");
}
ES6:
const callMe = () => {
console.log("Some text");
}
if you want to call this function when clicking the button you can't do this
<Button onClick={callMe()}>Print text</Button>
This will call the fuction callMe when the button is loaded once.
What you need to do to make it works is
<Button onClick={callMe}>Print text</Button>
Notice that there is no parenthesis after the function name which indicate that the function is not yet called.
In the following code:
document.getElementById( 'elem' ).addEventListener( 'blur', function() {
myScript();
});
How can I pass the document.getElementById( 'elem' ) object to myScript()? I was thinking of something like the keyword "this," so I can then act on the element in the callback function.
You have four ways to pass the object this
Bind the this object and call the function:
This approach should be used if you need to execute some logic before myScript() execution
function myScript() {
console.log(this.id);
}
document.getElementById('elem').addEventListener('click', function() {
myScript.bind(this)();
});
<button id="elem">Click me!</button>
Call the function myScript using function call:
This approach should be used if you need to execute some logic before myScript() execution
Also read about function Function.prototype.apply().
function myScript() {
console.log(this.id);
}
document.getElementById('elem').addEventListener('click', function() {
myScript.call(this);
});
<button id="elem">Click me!</button>
Pass the function directly:
function myScript() {
console.log(this.id);
}
document.getElementById('elem').addEventListener('click', myScript);
<button id="elem">Click me!</button>
Or pass the object this:
function myScript(element) {
console.log(element.id);
}
document.getElementById('elem').addEventListener('click', function() {
myScript(this); //Here you will need to use the param.
});
<button id="elem">Click me!</button>
Resource
Function.prototype.bind()
Function.prototype.call()
Function.prototype.apply()
Further to the answer from Ele, you should prefer the binding method. As dfsq said in the comment, you can go
element.addEventListener('click', function() {
myScript(element);
}
However, using an anonymous function like this means you won't be able to remove the event listener.
const element = document.getElementById('elem');
// creates a new function instance with element bound as first arg
const eventListenerCallback = myScript.bind(null, element);
element.addEventListener('click', eventListenerCallback);
function myScript(element, event) {
element.setAttribute('data-clicked', 'true');
// remove the event listener once it has been clicked
element.removeEventListener('click', eventListenerCallback);
}
I have a button with a onclick attribute which is pointing to the function test().
<button onclick="test()">Button 1</button>
<button onclick="test()">Button 2</button>
<button onclick="test()">Button 3</button>
Function test():
function test()
{
var button_name = this.html;
console.log("Im button "+ button_name);
}
How can I get informations about the clicked button?
e.g. How can i read the html?
jsfiddle: https://jsfiddle.net/c2sc9j9e/
Pass the this reference to the function, then read textContent property the text content of the node.
HTML
<button onclick="test(this)">Button 1</button>
Script
function test(clickedElement){
var button_name = clickedElement.textContent;
}
Fiddle
Four options:
Pass this into the function.
<button onclick="test(this)">Button 1</button>
and then use that argument in the function.
Hook up the handlers with addEventListener or jQuery's on, and then use this within the handler.
var buttons = document.querySelectorAll("selector-for-the-buttons");
Array.prototype.forEach.call(buttons, function(btn) {
btn.addEventListener("click", handler, false);
});
function handler() {
// Use `this` here
}
jQuery version:
$("selector-for-the-buttons").on("click", function() {
// Use `this` here
});
Hook up a single handler on a container these buttons are in, and use the target property of the event object to determine which was clicked (but note that if you use other elements within button, you'll need to loop up to the button first).
document.querySelector("selector-for-the-container").addEventListener("click", function(e) {
// Use `e.target` here
}, false);
jQuery version that handles the possibility of nested elements within the button for you:
$("selector-for-the-container").on("click", "button", function() {
// Use `this` here (note this is different from the DOM version above)
});
I came across an other extremely simple way to do it in Vanilla JS so I post it here for reference:
function whoami () {
var caller = event.target;
alert("I'm " + caller.textContent);
}
<button onclick="whoami()">Button 1</button>
<button onclick="whoami()">Button 2</button>
<button onclick="whoami()">Button 3</button>
I'm not sure about the browser support for it but it works at least on Safari, Firefox and Blink based browsers.
function test(button)
{
var button_name = button.getAttribute('name');
console.log("Im button "+ button_name);
}
<button onclick="test(this)" name="button1">Button 1</button>
<button onclick="test(this)" name="button2">Button 2</button>
<button onclick="test(this)" name="button3">Button 3</button>
If you want to use Jquery, then you can call the $(this) object in the function.
you must pass "this" to function
<button onclick="test(this)">1</button>
<button onclick="test(this)">2</button>
<button onclick="test(this)">3</button>
<script>
function test(t)
{
console.log(t);
}
</script>
Here is your solution jsfiddle , using jquery.
<button onclick="test(this)">1</button>
<button onclick="test(this)">2</button>
<button onclick="test(this)">3</button>
<script>
function test(button)
{
var button_name = $(button).html();
alert("Im button "+ button_name);
}
</script>
just add id to each button and pass it to your test function
and here is working jsfiddle
<button onclick="test(this.id)" id="button1">1</button>
<button onclick="test(this.id)" id="button2">2</button>
<button onclick="test(this.id)" id="button3">3</button>
<script>
function test(id)
{
var button_name = id;
alert("Im button name is : "+ button_name);
console.log("Im button name is :"+ button_name);
}
</script>
What you want is the event that triggers the click, and you do that by specifying the function call as MyFunction(event). For example:
<ul>
<li onclick="MyFunction(event)">Red</li>
<li onclick="MyFunction(event)">Orange</li>
<li onclick="MyFunction(event)">Yellow</li>
</ul>
and then your Javascript function can be:
function MyFunction(ev) {
// Now you have access to everything in the event
//- including the triggering element
var element = ev.srcElement;
}
By leaving out the (event) parameter in the specification of the onclick function call you don't get it.