Kingrune
Kingrune

Reputation: 87

How would you make multiple buttons in html point to the same JS function

I want 'div#Welcome a' and 'div#Familiarize a' to point to this JS code:

    e.preventDefault();
    var itemClicked = $(this);
    var id = itemClicked.attr("id");
    id = id.replace(/\D/g,'');
    slider.goToSlide(id);
    return false;

right now i have this:

$('div#Welcome a').click(function(e){

and this:

$('div#Familiarize a').click(function(e){

for the click to go to the specified code. I was wondering if there was a way that anything that i wanted to be linked with this could could be without having to make a new function every time. Is there an ID for certain tags that i can put on? Thank you in advance.

Upvotes: 0

Views: 56

Answers (3)

Steve Harris
Steve Harris

Reputation: 5109

You could also give each div the same class and attach the handler to that.

<div class="thisclass">

$('.thisclass').click(function (e) {

}

Upvotes: 0

Barmar
Barmar

Reputation: 782315

You can use multiple selectors together by separating them with comma.

$('div#Familiarize a, div#Welcome a').click(function(e) {
    e.preventDefault();
    var itemClicked = $(this);
    var id = itemClicked.attr("id");
    id = id.replace(/\D/g,'');
    slider.goToSlide(id);
    return false;
});

Although to simplify things, I suggest giving all the relevant DIVs a common class, and using that in the selector: $('div.tab a').click(...)

Upvotes: 1

Rob M.
Rob M.

Reputation: 36521

Make your code block into a named function and pass that to your event handlers:

function myEventHandler(e) {
    e.preventDefault();
    var itemClicked = $(this);
    var id = itemClicked.attr("id");
    id = id.replace(/\D/g,'');
    slider.goToSlide(id);
    return false;
}

$('div#Familiarize a').click(myEventHandler);
$('div#Welcome a').click(myEventHandler);

Or as @mark.hch and @Huangism have pointed out, you can also use comma-separated selectors:

$('div#Familiarize a, div#Welcome a').click(myEventHandler);

Upvotes: 5

Related Questions