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

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>

Related

document.removeEventListener javascript

How can I remove this type of listener?
document.addEventListener("onSomething", function(){
//Do something
});
when try to remove return number argument exception, way a function in second parameter but i not have a function.
document.removeEventListener("customUploadComplete")
You need to make a reference to the function in order to remove it. So pull it out into a function so you can remove it.
var thisThing = function(){
//Do something
}
document.addEventListener("onSomething", thisThing);
document.removeEventListener("onSomething", thisThing);
You need to declare a function in order to remove it. This is because you need to reference it upon removal so that the browser can recognize which event to remove.
This will not work:
btn.addEventListener("click", function() { alert("clicked") });
btn.removeEventListener("click", function() { alert("clicked") });
because there is no reference to the function. Each function is unique, even if they have the same code within them.
If you declare a function you can store a reference to that function, and then remove it:
function clickEvent() {
alert("clicked!");
}
btn.addEventListener("click", clickEvent);
btn.removeEventListener("click", clickEvent);
Here's an example:
let $ = document.querySelector.bind(document),
btn = $("#b1"),
add = $("#b2"),
remove = $("#b3");
function clickEvent() {
alert("click");
}
btn.addEventListener("click", clickEvent);
remove.addEventListener("click", function() {
btn.removeEventListener("click", clickEvent);
alert("event removed!");
});
add.addEventListener("click", function() {
btn.addEventListener("click", clickEvent);
alert("event added!");
});
<button id="b1">click me</button>
<p/>
<button id="b2">Add Event Listener</button> <button id="b3">Remove Event Listener</button>

single onclick function for buttons with a similar id pattern - JavaScript

I want to reduce the code.
function one() {
console.log("hai");
}
document.getElementById('dealsButton_1').onclick = one;
document.getElementById('dealsButton_2').onclick = one;
//I want the above 2 lines of code reduced to one.
A single function for on click on 'dealsButton_*' patterned id elements. How can I do this. The elements are dynamically loaded.
You can use querySelectorAll and the selector [id^=dealsButton_] to add the event listener in a single line - see demo below:
function one() {
console.log("hai");
}
Array.prototype.forEach.call(
document.querySelectorAll('[id^=dealsButton_]'), function(e) {
e.addEventListener('click', one);
});
<div id="dealsButton_1">one</div>
<div id="dealsButton_2">two</div>
If the markup is dynamically loaded you can base it on a static element like this:
function one() {
console.log("hai");
}
document.addEventListener('click', function(e) {
if (e.target && /^dealsButton_/.test(e.target.id))
one();
})
// dynamically add
document.body.innerHTML = `<div id="dealsButton_1">one</div>
<div id="dealsButton_2">two</div>`;
Are you looking for something like this:
function onClick(){
//single handler
}
$('[id*="dealsbutton_"]').click(onClick)
Here is a solution where you can choose ID name as u wish without a specific pattern of name.
<html>
<body>
<div id="abc">one</div>
<div id="def">two</div>
<script type="text/javascript">
function one() {
console.log("hai");
}
function addOnclickFunc (func, idArray){
idArray.forEach(function(element) {
document.getElementById(element).onclick = func;
})
}
addOnclickFunc(one,["abc","def"])
</script>
</body>
</html>
you use jQuery with regex for this
$.each( $("button[id^='dealsButton_']"), function () {
$(this).on('click', function(){
//code here
})
});
if want to make the function call names dynamically. pass it as data attribute to button element and call it using eval function
<button id="dealButton_1" data-click="one"></button>
$.each( $("button[id^='dealsButton_']"), function () {
$(this).on('click', function(){
var function_call = $(this).attr('data-click')
eval(function_call)
})
});

Override javascript click event one time

I would like to replace the default action of an click event for all anchors in a webpage.
When I use this piece of code:
<html> <head> <script>
var list=document.getElementsByTagName("a");
var isChecked = false;
function load () {
for (i=0; i<list.length; i++)
{
var old = (list[i].onclick) ? list[i].onclick : function () {};
list[i].onclick = function () {
if( !isChecked)
{
test();
old();
}
else
old();
};
}
}
function test() {
alert("new action");
isChecked = true;
}
</script> </head>
<body onload="load();">
<a id="nr_1" onClick="alert('test');"> Anchor 1 </A>
<a id="nr_2" onClick="alert('test2');"> Anchor 2 </A>
</body> </html>
When I click an anchor I get the alert out of the test function and then the default function of the second anchor (even when I click the first anchor). When I then again click one of the two anchors I always get the Alert from the second anchor.
How do I put the original onclick functions back for each anchor element? When someone has an solution in jquery I would be glad as well.
EDIT
I was succesfull using this code:
function load()
{
$('a').attr('disabled', 'disabled');
$('a').click(function(e){
if($(this).attr('disabled'))
{
alert("new");
e.preventDefault();
$('a').removeAttr("disabled");
this.click();
}
});
}
On loading of the page this function is called giving all anchor elements a "disabled" attribute. After clicking the element the e.preventDefault() function disables the inline onclick function. Then I remove the "disabled" attribute and call the click function of the element again. because now the element doesn't have a "disabled" attribute only the default function is performed. I'm still open for "more elegant" solutions to this problem, but for now I'm a happy camper!
If you use jQuery you can combine a one-time handler with a persistent handler:
Documentation for .one() and .on()
Working Example: http://jsfiddle.net/Q8gmN/
Sample HTML:
<input type="button" id="click" value="click" />
​
Sample JavaScript:
button.one('click', function () {
console.log('one time function fired');
});
button.on('click', function () {
console.log('persistent function fired');
});
​

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

Categories

Resources