Reputation: 87
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
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
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 DIV
s a common class, and using that in the selector: $('div.tab a').click(...)
Upvotes: 1
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