Paradoxis
Paradoxis

Reputation: 4708

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

Upvotes: 3

Views: 473

Answers (5)

Lars Beck
Lars Beck

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

Tim B James
Tim B James

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

aaron-bond
aaron-bond

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

Zword
Zword

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

A.T.
A.T.

Reputation: 26312

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

Upvotes: 5

Related Questions