Reputation: 4708
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();
});
});
I am a newbie.Thanks in advance for help
Upvotes: 3
Views: 473
Reputation: 3584
Why don't you use something like this? ;)
<button class="first">First</button>
<button class="second">Second</button>
$(function(){
$( '.first, .second' ).on( 'click', function() {
alert( 'You clicked me!' );
});
});
Upvotes: 0
Reputation: 20364
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();
Upvotes: 3
Reputation: 3341
foo is declared inside of the first click event. It will not be scoped and available for the second.
See this JS fiddle for the correct way to scope this function: http://jsfiddle.net/tRm3d/4/
var function foo() {}
should be outside of the click events.
Upvotes: 0
Reputation: 6793
You are calling a function within another function.So you cannot call it directly.See this fiddle: http://jsfiddle.net/tRm3d/1/
$(document).ready(function(){
$(".Original").click(function foo(){
alert("bar");
});
$(".Second").click(function(){
$(".Original").click().foo();
});
});
Upvotes: 2