I cant figure out why I am getting the error:
Error: TypeError: $.showMessage is not a function
File 1:
(function($) {
$.fn.showMessage = function(message, type, delay) {
var $messages = $("#messages");
type = (typeof type == 'undefined') ? 'info' : type;
delay = (typeof delay == 'undefined') ? 0 : delay;
var message_html = '<div class="messages"><ul>' +
'<li class="'+ type +'">' +
'<p>' + message + '</p><a href="#" class="close"></a>' +
'</li></ul></div>';
if($messages.length){
$messages.html(message_html).hide().delay(delay).fadeIn("fast");
} else {
$("#main h1").before(message_html).hide().delay(delay).fadeIn("fast");
}
return this;
};
})(jQuery);
File 2:
(function($) {
$.showMessage('test','success');
})(jQuery);
Note: it works fine if I have a each() and use a selector $("#messages").showMessage('test','success');. I read somewhere that you always need to return this although can’t figure how to do this without the each()
The below version works fine, although do I really need the each and to pass a selector?
$.fn.showMessage = function(message, type, delay) {
return this.each(function() {
var $this = $(this);
type = (typeof type == 'undefined') ? 'info' : type;
delay = (typeof delay == 'undefined') ? 0 : delay;
var message_html = '<div class="messages"><ul>' +
'<li class="'+ type +'">' +
'<p>' + message + '</p><a href="#" class="close"></a>' +
'</li></ul></div>';
if($this.length){
$this.html(message_html).hide().delay(delay).fadeIn("fast");
} else {
$("#main h1").before(message_html).hide().delay(delay).fadeIn("fast");
}
});
};
When you use the construct
$.fn.showMessage, you are declaring a jQuery plugin namedshowMessagethat will act on a given context, e.g.,$("#main").showMessage. To declare a plugin that can be called in a static way, that is, a helper method, you need to declare it outside of the$.fnnamespace: