Add multiple listeners in javascript [duplicate] - javascript

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>

Related

jquery .off(): how to remove a certain click handler only?

I've an element with two handler bound to it:
<button class="pippo pluto">
push me
</button>
$('.pippo').on('click', function () {
alert("pippo");
});
$('.pluto').on('click', function () {
alert("pluto");
});
I'm trying to .off() only one of them, but the syntax eludes me :-( I'm trying with something among the line of..
<button class="dai">
remove
</button>
$('.dai').on('click', function () {
$('.pippo').off('click');
alert("ok, removed");
});
but this removes both the handler. So I'm trying with...
$('.pippo').off('click .pippo');
but then nothing gets removed.
So I removed the middle space:
$('.pippo').off('click .pippo');
but back to square 1: both handler gets removed.
The right syntax would then be... ?
https://jsfiddle.net/6hm00xxv/
The .off(); method allows you to target multiple selectors as well as a specific event.
$('.pippo').off() would remove all events for the .pippo selector.
$('.pippo').off('click') would remove all click events for the .pippo selector.
$('.pippo').off('click', handler) would remove all click events with that handler for the .pippo selector.
In your case the handler used to add the event listener was an anonymous function so the handlercannot be used in the off() method to turn off that event.
That leaves you with three options, either use a variable, use a namespace or both.
Its quite simple to figure out which one to use.
if( "The same handler is needed more than once" ){
// you should assign it to a variable,
} else {
// use an anonymous function.
}
if ( "I intent to turn off the event" && ( "The handler is an anonymous function" || "I want to turn off multiple listeners for this selector at once" ) ){
// use a namespace
}
In your case
your handler is only used once so your handler should be an anonymous function.
you wish to turn off the event and your handler is anonymous so use a namespace.
So it would look like this
$('.pippo').on('click.group1', function () {
alert("pippo");
});
$('.dai').on('click', function () {
$('.pippo').off('click.group1');
alert("ok, removed");
});
It would work just as well to assign you handler to a variable if you prefer.
This allows you to specify which selector, eventType and handler to remove.
var pippo_click = function (e) {
alert("pippo");
});
$('.dai').on('click', function () {
$('.pippo').off('click', pippo_click);
alert("ok, removed");
});
But as a rule you shouldn't create variables if they're not needed.
One easier alternative with jQuery is to define a namespace for your click events:
$('.pippo').on('click.first', ...);
$('.pluto').on('click.second', ...);
// Remove only the pippo listener
$('.pippo').off('click.first');
Note that your classes pippo and pluto refer to the same element so using one or the other will not change anything.
https://jsfiddle.net/6hm00xxv/2/
Ok, solved. I just had to bind the handler to document:
function showMsg(text) {
alert("showMsg called with text: " + text);
};
$(document).on('click', '.pippo', function () {
showMsg("pippo");
});
$(document).on('click', '.pluto', function () {
showMsg("pluto");
});
$('.dai').on('click', function () {
$(document).off('click', '.pippo');
alert("ok, removed");
});
https://jsfiddle.net/6hm00xxv/1/
Because you are calling .off for click event. It is removing all possible click events on that selected element. The trick is to define a handler and remove that particular handler only.
function showPluto() {
showMsg("pluto");
};
function showPippo() {
showMsg("pippo");
};
function showMsg(text) {
alert("showMsg called with text: " + text);
};
$('.pippo').on('click', showPippo);
$('.pluto').on('click', showPluto);
$('.dai').on('click', function() {
$('.pippo').off('click', showPippo);
alert("ok, removed");
});

onclick calling two functions simultaneously?

here is my code..
<script type="text/javascript">
function clicker(){
var thediv=document.getElementById('downloadoverlay');
if(thediv.style.display == "none"){
thediv.style.display = "";
thediv.appendChild()
return false;
}
}
function clicker1(){
var thediv1=document.getElementById('downloadbox');
if(thediv1.style.display == "none"){
thediv1.style.display = "";
thediv1.appendChild()
return false;
}
}
</script>
on clicking the button.. the event should call two functions simultaneously.. help..??
Add the handlers unobtrusively, from within your script. Something like:
function addHandler(etype, el,handlerFunction){
if (el.attachEvent) {
el.attachEvent('on' + etype, handlerFunction);
} else {
el.addEventListener(etype, handlerFunction, false);
}
}
var myButton = document.getElementById('mybutton');
addHandler('click', myButton, clicker);
addHandler('click', myButton, clicker1);
Yes, you can, if you attach event listener: IE, other browsers.
Just keep in mind that they both won't end at the same moment, and one might get 'cut short', if site redirects, before second function is done.
Also, in this case, I would set CSS class on tag which contains both #downloadoverlay and #downloadbox. Instead of messing with style object directly.
Just write one function that calls both. For example, you could write
function onClick() {
clicker();
clicker1();
}
And set onclick="return onClick();" on the element you care about.
Just make another function to call both of them simultaneously
function callClickers(){
clicker();
clicker1();
}
Now add this to your button onclick
You can call the two functions at once for the onClick event
<button type="submit" id="mySubmit" onClick=" clicker(); clicker1()">Search</button>

How to call two methods on button's onclick method in HTML or JavaScript?

How to call two methods on button's onclick method in HTML or JavaScript ?
Try this:
<input type="button" onclick="function1();function2();" value="Call2Functions" />
Or, call second function at the end of first function:
function func1(){
//--- some logic
func2();
}
function func2(){
//--- some logic
}
...and call func1() onclick of button:
<input type="button" onclick="func1();" value="Call2Functions" />
As stated by Harry Joy, you can do it on the onclick attr like so:
<input type="button" onclick="func1();func2();" value="Call2Functions" />
Or, in your JS like so:
document.getElementById( 'Call2Functions' ).onclick = function()
{
func1();
func2();
};
Or, if you are assigning an onclick programmatically, and aren't sure if a previous onclick existed (and don't want to overwrite it):
var Call2FunctionsEle = document.getElementById( 'Call2Functions' ),
func1 = Call2FunctionsEle.onclick;
Call2FunctionsEle.onclick = function()
{
if( typeof func1 === 'function' )
{
func1();
}
func2();
};
If you need the functions run in scope of the element which was clicked, a simple use of apply could be made:
document.getElementById( 'Call2Functions' ).onclick = function()
{
func1.apply( this, arguments );
func2.apply( this, arguments );
};
The modern event handling method:
element.addEventListener('click', startDragDrop, false);
element.addEventListener('click', spyOnUser, false);
The first argument is the event, the second is the function and the third specifies whether to allow event bubbling.
From QuirksMode:
W3C’s DOM Level 2 Event specification pays careful attention to the problems of the traditional model. It offers a simple way to register as many event handlers as you like for the same event on one element.
The key to the W3C event registration model is the method addEventListener(). You give it three arguments: the event type, the function to be executed and a boolean (true or false) that I’ll explain later on. To register our well known doSomething() function to the onclick of an element you do:
Full details here: http://www.quirksmode.org/js/events_advanced.html
Using jQuery
if you're using jQuery, there is a nice API for event handling:
$('#myElement').bind('click', function() { doStuff(); });
$('#myElement').bind('click', function() { doMoreStuff(); });
$('#myElement').bind('click', doEvenMoreStuff);
Full details here: http://api.jquery.com/category/events/
<input type="button" onclick="functionA();functionB();" />
function functionA()
{
}
function functionB()
{
}
Hi,
You can also do as like below... In this way, your both functions should call and if both functions return true then it will return true else return false.
<input type="button"
onclick="var valFunc1 = func1(); var valFunc2 = func2(); if(valFunc1 == true && valFunc2 ==true) {return true;} else{return false;}"
value="Call2Functions" />
Thank you,
Vishal Patel

How to call multiple JavaScript functions in onclick event?

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>

How to apply multiple events to the same function

I'm not the best at this jquery stuff. But I'm trying to seperate the action from the function so I can apply multiple events that cause the same function. Unfortunately this isn't working. Anyone know why?
Updated Function, but still errors
$(document).ready(function() {
var $info_items = jQuery('.checkbox.has_info, .has_info');
$info_items.click(function(event) {
$(this).show_text(event);
});
// I suspect it has something to do with this initalizer of the function here
jQuery.fn.show_text = function(event){
var $info_item = jQuery(this);
$info_items.filter(function(index){
return $(".hidden_text").css("display","block");
}).not($info_item).parent().next().next().hide("slow");
$info_item.parent().next().next().show("fast");
});
});
What is e, the event? You need to name the event argument to the click() function to use it. Also, to invoke show_text such that it has a this, you need to invoke it on an element:
$info_items.click(function (event) {
// 'this' is the element in $info_items which was clicked
// invoke show_text on the element in question
$(this).show_text(event);
});
You also have an extra ) on your final }); line.
You can use jQuery bind to attach several events to a single function.
$('#whatever').bind('mouseover focus click', function() {
your_custom_function();
});
Are you looking for something like this?
var handle = function(event) {
$(event.currentTarget).show_text(event);
};
$info_items.bind('click blur', handle);

Categories

Resources