Reputation: 12650
I need to apply this script to work the same way for two other divs: This works well, but how can I make it do the same thing for two other elements without rewriting the entire thing for each?
$(".survey_option li > a").each().live('click', function (event) {
// First disable the normal link click
event.preventDefault();
// Remove all list and links active class.
$('.so_1 .active').toggleClass("active");
// Grab the link clicks ID
var id = this.id;
// The id will now be something like "link1"
// Now we need to replace link with option (this is the ID's of the checkbox)
var newselect = id.replace('partc', 'optionc');
// Make newselect the option selected.
$('#'+newselect).attr('checked', true);
// Now add active state to the link and list item
$(this).addClass("active").parent().addClass("active");
return false;
});
Upvotes: 0
Views: 455
Reputation: 4500
First, you don't need to call the .each()
method, .live()
will bind itself to all elements that your selector matches. So, all you need to do is match all the elements you want using selectors:
$(".survey_option li > a, #secondElement, #thirdElement > p").live('click', function (event) {
// do it all...
}
Upvotes: 2
Reputation: 1421
You can also wrap it as an object and extend it to other selectors.
Upvotes: 0
Reputation: 2291
You might want to make it a jQuery function for ease of calling...
$.fn.myFunct = function() {
$(this).each()...
}
Then call it on anything you like:
$("#this, .that, otherstuff").myFunct();
Upvotes: 1
Reputation: 131978
What about wrapping your function in another function, like so...
function modMyDiv(selectorClass) {
$("." + selectorClass + " li > a").each().live('click', function (event) {
// First disable the normal link click
event.preventDefault();
// Remove all list and links active class.
$('.so_1 .active').removeClass("active");
$('.so_2 .active').removeClass("active");
// Grab the link clicks ID
var id = this.id;
// The id will now be something like "link1"
// Now we need to replace link with option (this is the ID's of the checkbox)
var newselect = id.replace('partc', 'optionc');
// Make newselect the option selected.
$('#'+newselect).attr('checked', true);
// Now add active state to the link and list item
$(this).addClass("active").parent().addClass("active");
return false;
});
}
Then
modMyDiv('survey_option');
modMyDiv('other_class');
Upvotes: 2
Reputation: 268344
You can cause it to affect multiple elements by changing your selector:
$(".element_1, .element_2, .randomElement, #someOtherThing");
Note also that you don't need to call $.each()
before adding your $.live()
call. $.live()
will be applied to all of the matched elements, doing its own internal $.each()
logic.
$(".elem1, .elem2 > a, #someThing").live("click", function(e){
e.preventDefault();
alert($(this).text()); // works on all elements in the selector
});
Upvotes: 4