Return true or false from jQuery plugin

I am trying to write a simple jQuery plugin to check if the canvas is empty or not. However, I am having problems returning a boolean value.

(function ($) { $.fn.extend({ isBlank : function() { return this.each(function () { var context = this.getContext('2d'), imageData = context.getImageData(0, 0, this.offsetWidth, this.offsetHeight); for (var i = 0; i < imageData.data.length; i += 4) { if (imageData.data[i+3] !== 0) { return false; } } return true; }); } }); })(jQuery); 

For some reason, this returns a canvas object, not a boolean. However, when I take the code from each loop, it returns a boolean value as expected.

How can I make this work with each loop?

+4
source share
4 answers

It returns the canvas because this is what is returned from the isBlank function. return this.each(...) returns the jQuery object that isBlank was called isBlank .

You need to set the variable before .each , if necessary set it to true or false, and then return it.

Note. Inside .each , return false functions like break and return true function, such as continue .

Example:

 (function ($) { $.fn.extend({ isBlank : function() { var ret = true; this.each(function () { var context = this.getContext('2d'), imageData = context.getImageData(0, 0, this.offsetWidth, this.offsetHeight); for (var i = 0; i < imageData.data.length; i += 4) { if (imageData.data[i+3] !== 0) { ret = false; } } }); return ret; } }); })(jQuery); 
+3
source
 (function ($) { $.fn.extend({ isBlank : function() { var result = true; this.each(function () { var context = this.getContext('2d'), imageData = context.getImageData(0, 0, this.offsetWidth, this.offsetHeight); for (var i = 0; i < imageData.data.length; i += 4) { if (imageData.data[i+3] !== 0) { result = false; } } }); return result; } }); })(jQuery); 

Basically, pull out the extra return and return a single value at the end of the function.

+2
source

Your code causes a return to this.each , which should return the object you are calling .isBlank . I would delete the return for each and see if the behavior you expect is through and declare a variable outside the call to .each that is set to .each and returns instead, like the Rocket mentioned in its answer.

+1
source

By design, here your plugin is able to accept several elements. This is why you iterate over this .

What if you pass multiple objects, some empty, some not? Either the plugin code to take only one object, or consider changing how your plugin informs you of the status of the canvas. instead of returning false, you can add a class to empty elements or a data tag.

The methods in the above answers will work, but if you use them, I suggest changing the plugin name to "AreAllBlank ()"

0
source

Source: https://habr.com/ru/post/1385015/


All Articles