Can I have two JavaScript onclick events in one element? - 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

I want to call two functions from one onclick [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>

Override inline click event in jQuery

I have links in a navigation that look similar to this
<a id="navform" href="#" tabindex="-1" onclick="mojarra.ab(this,event,'action','#form','content');return false" class="active"><span>Policy</span></a>
I am checking for form changes and trying to disable the onclick event for the links when there are changes and enable them if once the user saves the form.
$(':input').on('change', function() {
formChanged = true;
});
$('nav a').on('click', function(e){
if(formChanged){
e.preventDefault();
$(this)[0].onclick = null;
}
});
I have tried preventDefault and nulling the event according to some answers I found on here, but no luck. Could someone please tell me how to fix this?
UPDATE:
Thanks to all your answers, I got some ideas and figured how to fix it:
if($('.policy-form')){
$(':input').on('change', function() {
formChanged = true;
$('nav a').each(function(){
var handler = $(this).attr('onclick');
$(this).removeAttr('onclick');
$(this).on('click',function(){
if(formChanged){
invokeDialog("warning");
formChanged = false;
$(this).attr('onclick', handler);
}
});
});
});
Plain JavaScript one-liner
Use
document.getElementById('navform').onclick = null;
This is because only the last onclick defined will run and here we override it with null.
Note that it would be way better if you would just avoid onclick in your HTML, or if you would at least modify mojarra.ab() appropriately, so that it performs any actual actions only when you desire.
Demo:
document.getElementById('one').onclick = null;
<a id="one" href="#" onclick="alert(true)">Doesn't alerts</a>
<br/>
<a id="two" href="#" onclick="alert(true)">Does alerts</a>
EDIT
Vide comment, here is an example of toggling old onclick on and off:
var button = document.getElementById('button');
var oldOnclick = button.onclick;
document.getElementById('toggle').addEventListener('click', function() {
button.onclick = button.onclick !== null ? null : oldOnclick;
})
<input id="button" type="button" onclick="alert('Test')" value="Alert"/>
<br/>
<br/>
<input id="toggle" type="button" value="Toggle above button"/>
$('nav a').on('click', function(e){
$(this).removeAttr('onclick'); // add this line to remove inline onclick
if(formChanged){
e.preventDefault();
$(this)[0].onclick = null;
}
});
You can use the .off() method:
$('nav a').off('click');
One good practive is to add an namespace to your events.
$('nav a').on('click.somenamespacehere', function(e){
});
...
$('nav a').off('click.somenamespacehere');
In this case, you can specify later which events you want to remove (with the off method)
You can't do it that way because the on('click' event and the inline one are two different events and there's no way to tell which would happen first. But, you could replace the inline handlers with your own handler like so
on('click', function(e) {
if (formChanged) {
mojarra.ab(...);
}
});
With an inline click function there are many possibilities to control the logical flow or order of executing the functions attached to the same event.
One possibility is to change the inline code so that you can define a first function and based of the result of this you may decide if execute or not the next function.
My snippet:
// assuming the inline onclick function is like:
function mojarra_ab(_this, event, _action, _form, _content) {
$('<p>Executed function: mojarra_ab</p>').appendTo('body');
}
function myNewClick() {
$('<p>Executed function: myNewClick</p>').appendTo('body');
if ($('#yesNo option:selected').val() == 'true') {
return true; // return true to execute the mojarra_ab function
}
return false; // return false if you don't need to execute the mojarra_ab function
}
$(function () {
$('nav a').attr('onclick', function(index, attr) {
return 'if (myNewClick() == true) {' + attr + '}';
});
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
Choose if to run myNewClick and then mojarra_ab: <select id="yesNo">
<option value="true" selected>True</option>
<option value="false">False</option>
</select>
<nav>
<a id="navform" href="#" tabindex="-1" onclick="mojarra_ab(this,event,'action','#form','content');return false"
class="active"><span>Policy</span></a>
</nav>

Pass a reference of the button I'm clicking into the func it triggers. JS

How do I pass a reference of the button I am clicking into the function it triggers?
jQuery('<button class="btn"/>')
.click(function() {
myFunc(this??);
return false;
})
var myFunc = function (this??) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if(jQuery(this??).parent().hasClass('myClass')){
//DO STUFF HERE
}
}
I can't use the class name as there are several of these buttons on my page.
Use myFunc(this). Its correct way to passs the element to your function
Use any other name other than this for your function parameter.
jQuery('<button class="btn"/>')
.click(function () {
myFunc(this);
return false;
});
var myFunc = function (elem) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if (jQuery(elem).parent().hasClass('myClass')) {
//DO STUFF HERE
}
}
No need to pass it in a separate function
jQuery('<button class="btn"/>')
.click(function() {
if(jQuery(this).parent().hasClass('myClass')){
//DO STUFF HERE
}
return false;
})
Remove ?
jQuery('<button class="btn"/>')
.click(function() {
myFunc(this);
return false;
})
var myFunc = function (obj) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if(jQuery(obj).parent().hasClass('myClass')){
//DO STUFF HERE
}
}
this is a reserved word and cannot be used as a variable (which is what you're attempting to do within your myFunc function. Change the name of your variable in your myFunc declaration:
var myFunc = function (myElement) { ... }
Then change your if statement to reflect that change:
jQuery(myElement).parent().hasClass('myClass')
I dont have much knowledge about jquery but a possible solution using Js is
<script>
function onClick1(b)
{
alert(b.parentNode.className);
}
</script>
<div class="divClass">
<button onclick="onClick1(this)">
hello
</button>
</div>
we can pass "this" in the onclick event attribute, which passes the reference object of the element generating the event (in this case button). We then can reference the parentNode of button and its class with className property.
HTML
<div class="myClass">
<button id="btn" class="btnClass">Hi</button>
</div>
JS
$('.btnClass').click(function() {
myFunc(this);
});
var myFunc = function (a) {
//I WANT TO CHECK IF THE BUTTONS PARENT HAS A SPECIFIC CLASS HERE
if(jQuery(a).parent().hasClass('myClass')){
alert();
//DO STUFF HERE
}
}
Check This Example

Set onclick event using script

I want to make my script set the onclick properity of a <div>.
I use this Html code:
<div id="forgotpass">Forgot Password?</div>
I want when a user clicks the <div> a forgotpass() function to run, but I do not want to use this:
<div id="forgotpass" onclick="forgotpass();">Forgot Password?</div>
Alternatively, if you're not using jQuery:
document.getElementById('forgotpass').onclick = forgotpass;
Pure JavaScript:
function addListener(element, eventName, handler) {
if (element.addEventListener) {
element.addEventListener(eventName, handler, false);
}
else if (element.attachEvent) {
element.attachEvent('on' + eventName, handler);
}
else {
element['on' + eventName] = handler;
}
}
function removeListener(element, eventName, handler) {
if (element.addEventListener) {
element.removeEventListener(eventName, handler, false);
}
else if (element.detachEvent) {
element.detachEvent('on' + eventName, handler);
}
else {
element['on' + eventName] = null;
}
}
addListener(document.getElementById('forgotpass'), 'click', forgotpass);
jQuery:
$(document).ready(function() {
$("#forgotpass").click(forgotPass);
});
Or:
$(document).ready(function() {
$("#forgotpass").click(function() {
forgotPass();
});
});
Something like this might work..
var div = document.getElementById("forgotpass");
div.onclick=function(){ /*do something here */ };
if you dont add the function, the javascript will run the onclick once it runs through the script.
You can do it with jQuery like
$("#forgotpass").click(function() {
alert("Handler for .click() called.");
});
In pure javascript you can do:
function forgotpass() {
//..code
}
var el = document.getElementById("forgotpass");
el.onclick = forgotpass;
but this is very naive, not flexible and probably a bad practice.
If you are using jQuery, you can do:
function forgotpass() {
//..code
}
$(document).ready(function() {
$("#forgotpass").click(function() {
forgotPass();
});
});
If you only need to support IE 9+ (source), you can use EventTarget.addEventListener in pure JavaScript.
function forgotpass() {
alert("Hello, world!");
}
var element = document.getElementById("forgotpass");
element.addEventListener("click", forgotpass, false);
<button id="forgotpass">Forgot Password?</button>
If you need to support older browsers, I recommend Speransky Danil's answer.
Adding event-listner directly in the HTML :
...
<div>
<input type="button" value="Set Cookie" onclick="setCookie();" />
</div>
<script>
function setCookie() {
console.log('ready to set cookie?');
}
</script>
...
Reference : W3CSchools
Good Luck!
If you are using jQuery it's best if done as follows. If the function call is executed more than once multiple eventhandles will be registered. Following approach makes sure the previous handlers are removed
$("#forgotpass").off().on('click', function () {
forgotPass();
});

Calling javascript function

I have the problem, that my javascript function isnĀ“t when I press the button:
<script type="text/javascript" language="javascript">
(function ($) {
$.fn.addToList = function (opts) {
var input = $(this);
opts.button.click(function () {
opts.list.append("<li>" + input.val() + "</li>");
});
};
}(window.jQuery));
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
</script>
and
<input type="text" id="zutat" name="zutat"></input>
<input type="button" id="btn" value="Click">
<ul id="list"></ul>
How do I call this javascript function? What is my problem?
If your script tag is before the #zutat" stuff, then you are trying to manipulate on #zutat when the DOM elements are not ready yet. In this case, When the jQuery selector is being executed, it will not match the elements, since they are not available yet.
To fix it, you should wrap your codes by the $(document).ready function or put it at the bottom of body tag.
<script type="text/javascript" language="javascript">
(function($) {
$.fn.addToList = function(opts) {
var input = $(this);
opts.button.click(function() {
opts.list.append("<li>" + input.val() + "</li>");
});
};
$(document).ready(function() { // <<<<<<< execute after document ready.
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
});
})(window.jQuery);
</script>
I think you should move the parenthesis this way
})(window.jQuery);
In Firefox (I am using Firebug to test this) if you do this
function(){ alert("GONG"); }();
It gives you an error but if you wrap the function with parenthesis
(function(){ alert("GONG"); })();
The anonymous function will be executed.
You should also wrap the call to the dom elements in a $(document).ready(); call as showed in qiao's answer.
if you want to add <li>s to a <ul> when you click a button, you are going about it in a very round about way. you don't need to extend jquery or object prototype to do that.
try the following
$("#button").click(function() {
var val = $("zutat").val();
$("#list").append($("<li>" + val + "</li>"));
});
Normally the click event is handled like this
$('#btn').on("click",function(){
// code
});
I don't know what your code does exactly but not that what you want.

Categories