onclick calling two functions simultaneously? - javascript

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>

Related

How do I add another onclick function after the vote function? [duplicate]

Can we put two JavaScript onclick events in one input type button tag? To call two different functions?
This one works:
<input type="button" value="test" onclick="alert('hey'); alert('ho');" />
And this one too:
function Hey()
{
alert('hey');
}
function Ho()
{
alert('ho');
}
.
<input type="button" value="test" onclick="Hey(); Ho();" />
So the answer is - yes you can :)
However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
The HTML
click
And the javascript
// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
if (window.addEventListener) {
return function(target, type, listener){
target.addEventListener(type, listener, false);
};
}
else {
return function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
}
}());
// find the element
var el = document.getElementById("btn");
// add the first listener
on(el, "click", function(){
alert("foo");
});
// add the second listener
on(el, "click", function(){
alert("bar");
});
This will alert both 'foo' and 'bar' when clicked.
There is no need to have two functions within one element, you need just one that calls the other two!
HTML
<a href="#" onclick="my_func()" >click</a>
JavaScript
function my_func() {
my_func_1();
my_func_2();
}
You can attach a handler which would call as many others as you like:
<a href="#blah" id="myLink"/>
<script type="text/javascript">
function myOtherFunction() {
//do stuff...
}
document.getElementById( 'myLink' ).onclick = function() {
//do stuff...
myOtherFunction();
};
</script>
You could try something like this as well
<a href="#" onclick="one(); two();" >click</a>
<script type="text/javascript">
function one(){
alert('test');
}
function two(){
alert('test2');
}
</script>

Add multiple listeners in javascript [duplicate]

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>

Perform click event for only one button under a CSS class

I have some JavaScript to execute logic i.e. doSomething() when a button is clicked. I know the class of the buttons, but there are multiple buttons on the page with this same class. The problem with my code below is that the doSomething() function is executed once for every button on the page when I only want it to execute one time only.
var myButtonClass = $(".my-button-class");
if (myButtonClass) {
myButtonClass.click(function (event) {
if (someCondition) {
doSomething();
}
});
}
I know it would be better to select by button div, but the button div names all vary based on how many there are (i.e. #my-button-div1, #my-button-div2, etc.) and the number of buttons is indefinite.
Is there a way to only do this event once? I don't care which button in the class happens to be clicked, I just need the event to fire once and then it's done.
UPDATE: To be clear, I still want the logic to execute if the user clicks another button on the page again, so I don't want to completely unbind the event. I just don't want it to execute once for every button on the page. For example, let's say I have 4 buttons. Right now it's doing something like the following when just one button is clicked:
alert!
alert!
alert!
alert!
I only need ONE of those alerts. Basically, whenever the user clicks any of the buttons on the page, I need it to go alert! only once per click.
Revised so that you don't have weird if statements, and allows for other click handlers to happily work if binded elsewhere
UPDATED:
var clickHandler = function handleClick(event) {
doSomething();
}
var bindClicks = true;
function doSomething() {
alert('alert!');
}
function doTheBinding() {
if (bindClicks) {
$('.my-button-class').on('click', clickHandler);
bindClicks = false;
}
}
// as many times as you want but it will still call once
doTheBinding();
doTheBinding();
doTheBinding();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="my-button-class">Click me!</button>
<button class="my-button-class">Click me!</button>
<button class="my-button-class">Click me!</button>
<button class="my-button-class">Click me!</button>
You can use on() and off() to bind and unbind the event on an element respectively.
$('.my-button-class').on('click', function (event) {
if (someCondition) {
doSomething();
// Unbind the event on all the elements having the class
$('.my-button-class').off('click');
// To unbind the event on only the clicked element
// $(this).off('click');
}
});
Sidenote: if (myButtonClass) { will always evaluate to true. jQuery returns an object even when the element is not found and an object is always truthy. To check if an element exists in DOM, use length property on the jQuery object $('someSelector').length > 0.
If you give the handler a local boolean variable that is protected with a closure, you can create a function that will execute only once. See this SO answer.
Run the code snippet below to see it in action.
$(".my-button-class").click(function() {
var executed = false;
return function() {
if (!executed) {
executed = true;
doSomething();
}
};
}());
function doSomething() {
alert("You should only see me once!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="my-button-class">Click me!</button>
<button class="my-button-class">No click me!</button>
UPDATE: To address a different issue of the click event getting bound more than once. Just do a similar thing with:
var bind = function() {
var bound = false;
return function() {
if (!bound) {
bound = true;
$(".my-button-class").click(function() {
if (someCondition)
doSomething();
});
}
};
}();
bind();
bind(); // won't execute second time
var someCondition = true;
function doSomething() {
$("#output").append("<br>alert!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="my-button-class">Click me!</button>
<button class="my-button-class">No click me!</button>
<span id="output"></span>

jQuery unbind click event function and re-attach depending on situation

The code below I use to create a sliding menu. I need to know how to unbind the function attached to the click event and re-attach it some other time. (using jQuery 1.7.2)
$(document).ready(function(){
$('.section').hide();
$('.header').click(function(){
if($(this).next('.section').is(':visible'))
{
$('.section:visible').slideUp()
$('.arrows:visible').attr("src","right.gif")
}
else
{
$('.section').slideUp();
$(this).next('.section').slideToggle();
$(this).find('.arrows').attr("src","down.gif")
});
});
The code below is what I have so far
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').unbind('click');
}
else
{
//else re-attach functionality?
}
});
Thanks
Simply make a named function. You can go low tech here and back to basics to unbind and reattach specific events.
function doStuff()
{
if($(this).,next('.section').is(':visible'))
...
}
$('.header').on('click', doStuff);
$('.header').off('click', doStuff);
Instead of unbind and re-bind, I suggest you to add a simple class to .header and check for the class in the click handler. See below,
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').addClass('dontClick');
} else {
$('.header').removeClass('dontClick');
}
});
And in your .header click handler,
$('.header').click(function(){
if ($(this).hasClass('dontClick')) {
return false;
}
//rest of your code
If you insist on having a unbind and bind, then you can move the handler to a function and unbind/bind the function any number of time..
You can try something like this.
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').addClass('clickDisabled');
}
else
{
$('.header').removeClass('clickDisabled');
}
});
And then in the click handler check for this class.
$(document).ready(function(){
$('.section').hide();
$('.header').click(function(){
if(!$(this).hasClass('clickDisabled')){
...
...
}
});
});
Why not make that top section a function, and then call it in your else statement?
You could try setting a variable as a flag. var canClick = ($('#formVersion').val() != 'Print'); Then in the click handler for your .header elements check to see if canClick is true before executing your code.
If you still want to remove the handler you can assign the events object to a variable. var eventObj = #('.header').data('events'); That will give you an object with all the handlers assigned to that object. To reassign the click event it would be like $('.header').bind('click', eventObj.click[0]);
After trying so hard with bind, unbind, on, off, click, attr, removeAttr, prop I made it work.
So, I have the following scenario: In my html i have NOT attached any inline onclick handlers.
Then in my Javascript i used the following to add an inline onclick handler:
$(element).attr('onclick','myFunction()');
To remove this at a later point from Javascript I used the following:
$(element).prop('onclick',null);
This is the way it worked for me to bind and unbind click events dinamically in Javascript. Remember NOT to insert any inline onclick handler in your elements.
You could put all the code under the .click in a separated function
function headerClick(){
if($(this).next('.section').is(':visible'))
{
$('.section:visible').slideUp()
$('.arrows:visible').attr("src","right.gif")
}
else
{
$('.section').slideUp();
$(this).next('.section').slideToggle();
$(this).find('.arrows').attr("src","down.gif")
}
}
and then bind it like this:
$(document).ready(function(){
$('.section').hide();
$('.header').click(headerClick);
});
$('#printVers').click(function(){
if($('#formVersion').val() != "Print")
{
$('.header').unbind('click');
}
else
{
$('.header').click(headerClick);
}
});

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>

Categories

Resources