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've created the function below to identify an onclick event which is dynamically generated with each page load. I'm able to get the onclick event into a variable (developer console output shown below). I want to execute that onclick event but can't find a good way of doing that. Any assistance is appreciated.
"ƒ onclick(event) {
mstrmojo.dom.captureDomEvent('*lK1129*kWA92AF1C396244F28902B3171F9642E57*x1*t1530820506700','click', self, event)
}"
function applyAll() {
//Get the self Link to click it
var linkBys = document.getElementsByClassName("mstrmojo-DocTextfield-valueNode");
// loop through each result
for(y = 0;y < linkBys.length;y++){
// retrieve the current result from the variable
var linkBy = linkBys[y];
// check the condition that tells me this is the one I'm looking for
if(linkBy.innerText.indexOf("link") !== -1){
// Find the right class
var idy = document.getElementsByClassName("mstrmojo-DocTextfield-valueNode")[y].onclick;
console.log(idy);
}
}
}
If the property 'onclick' is defined as a function, you can just run it as a function.
var idy = document.getElementsByClassName("")[y].onclick();
You could also handle it another way:
var idy = document.getElementsByClassName("")[y].onclick;
idy();
onclick is not an event, it's a function which gets executed when element is clicked. If you want to simulate click you can do element.click()
If you used:
element.addEventListener('click',()=>...);
instead of:
element.onclick=()=>...
then all you have to do is:
document.getElementsByClassName("mstrmojo-DocTextfield-valueNode")[y].dispatchEvent(new Event('click'));
You can call the function returned , adding parens:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function foo() {
var idy = document.getElementsByClassName("mstrmojo-DocTextfield-valueNode")[0].onclick;
console.log(idy);
idy();//like so
}
function alertMe() {
alert('Hello');
}
</script>
</head>
<body>
<button id="btn" class="mstrmojo-DocTextfield-valueNode" onclick="alertMe();">No click</button>
<button id="btn2" onclick="foo()">Click me</button>
</body>
</html>
let's suppose the browser rendered following page
<html>
...
<body>
<div id="partialContainer">
<script>
function saveItems(){
/* do somthing*/
}
</script>
<input type="button" id="btnTest" name="btnTest" value="Test" onclick="saveItems()"/>
</div>
</body>
</html>
after an AJAX call and change the "partialContainer" content using
$("#partialContainer").html(returnedMarkup)
saveItems function still remains in page and can get executed
how can remove this function when markup get replaced to avoid name colissioning
var saveItems = function () {}
After your Ajax, assign some other value to it, preferably the one above.
Try setting saveItems to undefined
$("#partialContainer").html(returnedMarkup);
if (!!saveItems && $.isFunction(saveItems)) saveItems = void 0;
You could put your function in an object literal:
var obj = { saveItems: function() { } }
and delete it after the ajax
delete obj.saveItems
On your ajax success callback function, just do:
$("#btnTest").prop( "onclick", null );
Be aware that $.removeAttr('onclick') will fail in ie 6-8, so .prop() is better.
EDIT: Just an example. I need support for if/else
I want to do this:
<button onclick="function() {alert('Hi!');prompt('What can I do for you?', 'make a Sandwich');}">Hello World!</button>
Apparently this doesn't work.
Do you know how I could do this?
How can I "call" a new function?
I cannot simply define it in a <script></script>-node.
You don't need a function to call. You can directly use Javascript code. This is considered bad practice.
<button onclick="alert('Hi!'); prompt('What can I do for you?','make a Sandwich');">
Hello World!
</button>
Demo
You can also use function as event handler as follow:
HTML
<button onclick="fnHandler();">
Hello World!
</button>
Javascript
function fnHandler() {
alert('Hi!');
prompt('What can I do for you?','make a Sandwich');
}
Demo
Using addEventListener you can bind events from javascript instead of inline in the HTML(Recommended):
HTML
<button id="myButton">
Hello World!
</button>
Javascript
document.getElementById('myButton').addEventListener('click', function() {
alert('Hi!');
prompt('What can I do for you?','make a Sandwich');
});
Demo
It is not recommended to write the functions inside the parameter. It is better to write them on a separate function and then link it with one of the methods listened above. You can still do what you said in the example by using the anonimous function like this:
<button onclick='(function(){
alert("hello world");
prompt("I am the Doctor","oh yeah");
})()'></button>
Updated version for general function because add listner adds uniqueness for click
<button onclick="function_name() id="button">Some Text</button>
Now to write the function definition in js
function function_name(){ .... statements; }
A typical example using this with if-else
<script>
document.getElementById('button').onclick = function() {
if (Calc.Input.value == '' || Calc.Input.value == '0') {
window.alert("Please enter a number");
} else {
document.getElementById('button').value=' Justera längd ';
}
return false;
}
</script>
Why clicking the button fires the alert? It is assigned to the paragraph, not button.
HTML:
<button onclick="foo()">Click me</button>
<p id="hidden" style="display:none"> I was hidden </p>
Javascript:
function foo(){
document.getElementById("hidden").style.display = "block";
document.getElementById("hidden").onclick = innnerClick();
}
function innnerClick(){
alert("Ouch! That hurt!")
}
Because of this line:
// ----------------------------------------------------vv
document.getElementById("hidden").onclick = innnerClick();
Here you call the innnerClick function immediately.
Just remove () after to pass the reference to a function instead of calling it, i.e.
document.getElementById("hidden").onclick = innnerClick;
Since, you need to add the reference of the function like this:
function foo(){
document.getElementById("hidden").style.display = "block";
document.getElementById("hidden").onclick = innnerClick;
}
not directly calling it.
Fiddle Demo
In jQuery, we can reproduce the same issue like:
$('button').click(function () {
$('#hidden').show();
$('#hidden').click(innnerClick()); <-- see the function with () here
});
Fiddle Demo
The issue is same here, we just need to pass the function reference to click handler here like:-
$('#hidden').click(innnerClick);
Fiddle Demo