Grigor
Grigor

Reputation: 4049

jQuery call same function when two different buttons are clicked

I have a button with class try and when its clicked there is a function that is being called, now I want to create a button called start that will do the same, and I don't want to copy paste whole code in that button click handler, is there a way to say lets say if try or start do the following in jquery?

Upvotes: 2

Views: 6867

Answers (4)

Roko C. Buljan
Roko C. Buljan

Reputation: 206048

just do:

$('#start, .try').on('click', function(){ // both of them
   myFunction();
});

or:

$('#start').on('click', function(){
   $('.try').click();         // trigger .try action
});


Or just call your function inside the click:

function myClickFunction(){
   // your code ...
}

$('#start').on('click',function(){
   myClickFunction();
});

Upvotes: 1

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

$('.start, .try').click(function(){
//do your thing here
});

assumes two buttons with different classes:

<button class='try'>try</button>
<button class='start'>start</button>

MUCH easier if you use one class:

<button class='trystart'>try</button>
<button class='trystart'>start</button>

$('.trystart').click(function(){
//do your thing here
});

Upvotes: 2

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Move the handler code to a named function and bind the named function.

function someFunction() {
}

$('.try').on('click', someFunction);
$('.start').on('click', someFunction);

Or in one line,

$('.try, .start').on('click', someFunction);

Upvotes: 2

Dutchie432
Dutchie432

Reputation: 29160

I assume that since you said a button called start that start is the id. That is why I am using a # instead of a . to reference it.

$('.try, #start').click(function(e){
    YourFunction();
});

if start is the class, then use this. # indicates an id, while . indicates a class.

$('.try, .start').click(function(e){
    YourFunction();
});

Upvotes: 9

Related Questions