I'm trying to make a function in JQuery run through calling it with two buttons. The first button runs the function as expected and the second button calls the function used by the first button, however it's not working.
This is my code:
-----------------HTML-----------------
<button class="Original">Original</button>
<button class="Second">Second</button>
----------------JQuery----------------
$(document).ready(function(){
$(".Original").click(function foo(){
alert("bar");
});
$(".Second").click(function(){
foo();
});
});
JSFiddle Example
I am a newbie.Thanks in advance for help
try simulating click of $(".Original") on $(".Second") click
$(".Second").click(function(){
$(".Original").click();
});
foo() method is only delegated to $(".Original") click event, it is unknown outside.
here is updated fiddle
My two cents.
Not sure why you don't just have the function declaration outside of the event handler. e.g.
// declare the function
var foo = function(){
alert('bar');
};
// bind click event handler for Original
$('.Original').click(foo);
// bind click event handler for Second
$('.Second').click(foo);
// call the function from anywhere
foo();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With