I'm creating a jQuery plugin that interacts with Bootstrap, and I get the following error when I call the function on a jQuery element:
Uncaught TypeError: Object [object Window] has no method 'each'
This is the JavaScript in question:
!function ($) {
$.fn.alertAutoClose = function (interval) {
setTimeout(function () {
return $(this).each(function () {
$(this).hide();
});
}, interval);
}(window.jQuery);
This is how the plugin is triggered:
$(".alert").alertAutoClose(1000);
This is the HTML on the page:
<div class="alert fade in">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Warning!</strong> Best check yo self, you're not looking too good.
</div>
Inside of setTimeout(), this is window, not your object. You would need to save the this reference and do something like this:
!function ($) {
$.fn.alertAutoClose = function (interval) {
var self = this;
setTimeout(function () {
self.hide();
}, interval);
return this;
}(window.jQuery);
FYI, you can also accomplish the same thing like this:
!function ($) {
$.fn.alertAutoClose = function (interval) {
this.delay(interval).hide(1);
return this;
}(window.jQuery);
When you give .hide() a duration, it turns into an animation so it will work with .delay().
Also, the this value inside a jQuery method is the jQuery object. So, if you want to call a method that applies to all elements in the jQuery object, you can just call the method directly on this. You don't have to turn it into a jQuery object (it already is one) and you don't have to use .each() because most jQuery methods (like .hide() already operate on all elements in the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With