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(),thisiswindow, not your object. You would need to save thethisreference and do something like this:FYI, you can also accomplish the same thing like this:
When you give
.hide()a duration, it turns into an animation so it will work with.delay().Also, the
thisvalue 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 onthis. 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.