Bind to jQuery event only for particular elements
Question
I am relatively new to jQuery but the below code seems logical but is not working as I would expect. I am utilizing the Colorbox jQuery plugin.
My intention is to only add a listener for the 'cbox_closed' event on 'a' elements who have an id that contains 'Remove'. Unfortunately, as presently implemented this adds the listener on all raisings of the 'cbox_closed' event.
Am I missing something or is this not a valid means of adding an event listener?
$('a[id*="Remove"]').bind('cbox_closed', function() {
var row = $($.fn.colorbox.element()).parents('tr');
row.fadeOut(1000, function() {
row.remove();
});
});
Solution
Try this:
$(document).bind('cbox_closed', function() {
if ( $( $.fn.colorbox.element() ).attr('id').match('Remove') ){
alert('Remove me!');
}
})
The event will always trigger when the ColorBox is closed. You would have to modify the plugin itself to prevent this event from firing in specific cases. So, the above code binds to the event then looks for your specific ID. I hope my explanation helps :)
OTHER TIPS
Shouldn't that be
$("a[id*='Remove']").bind('cbox_closed', function() {
You seem to be missing qoutes around the Remove
value
Or I misunderstood your problem