Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to run JQuery function

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

like image 337
Paradoxis Avatar asked Feb 09 '26 23:02

Paradoxis


2 Answers

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

like image 59
A.T. Avatar answered Feb 12 '26 16:02

A.T.


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();
like image 21
Tim B James Avatar answered Feb 12 '26 14:02

Tim B James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!