Reputation: 6934
I'm sorry for the general title, but I don't realy know how to call it.
Here is my code, that I want to reduce:
$('.ShowDialogIcon').click(function() {
$('.show_dialog').slideDown('fast');
return false;
});
$('.ShowDialogIcon2').click(function() {
$('.show_dialog2').slideDown('fast');
return false;
});
$('.ShowDialogIcon3').click(function() {
$('.show_dialog3').slideDown('fast');
return false;
});
$('.ShowDialogIcon4').click(function() {
$('.show_dialog4').slideDown('fast');
return false;
});
Now I see, that this is a bit unefective, what I would like to do is:
$('.ShowDialogIcon').showDialog('.showDialog');
$('.ShowDialogIcon2').showDialog('.showDialog2');
$('.ShowDialogIcon4').showDialog('.showDialog3');
$('.ShowDialogIcon4').showDialog('.showDialog4');
And what I've come up with is:
jQuery.fn.showDialog = function(cls) {
$(this).click(function() {
$(cls).show('fast');
});
}
And it doesn't work, can anyone help please?
Thanks, Mike.
Upvotes: 1
Views: 467
Reputation: 105081
You're setting click event on the wrong element.
This is an equivalent to your functionality:
jQuery.fn.extend({
showDialog: function(cls) {
this.click(function(evt){
evt.preventDefault();
$(cls).slideDown("fast");
});
}
});
To stop event bubbling it's better to use preventDefault
function on the event itself than returning false. This way you can safely avoid browsers' particularities.
Upvotes: 5
Reputation: 26554
My usual approach to this situation is first give a class that all dialog icons share and add an attribute to the dialog icon that points to the dialog that you want to show. For instance:
<a href="#show_dialog1" class="ShowDialogIcon">Show first</a> //href points to the dialog that will slide
<a href="#show_dialog2" class="ShowDialogIcon">Show first</a>
$(".ShowDialogIcon").click(function(){
//use the href attribute
var dialog = $(this).attr("href").replace("#",".");
$(dialog).slideDown("fast"); //slidedown
return false;
});
Upvotes: 0
Reputation: 126082
If you want to set up a jQuery plugin to do this:
(function($) {
$.fn.showDialog = function(cls) {
this.click(function() {
$(cls).show('fast');
return false;
});
});
})(jQuery);
$("#foo").showDialog(".bar");
See here for how to author a plugin.
Upvotes: 0