Using a watermark plugin for jQuery, I’m attempting to jslint and minimize the functions but I’ve come across syntax I have never seen before wherein there are expressions where there really ought to be an assignment or function call:
(function($) {
$.fn.watermark = function(css, text) {
return this.each(function() {
var i = $(this), w;
i.focus(function() {
w && !(w=0) && i.removeClass(css).data('w',0).val('');
})
.blur(function() {
!i.val() && (w=1) && i.addClass(css).data('w',1).val(text);
})
.closest('form').submit(function() {
w && i.val('');
});
i.blur();
});
};
$.fn.removeWatermark = function() {
return this.each(function() {
$(this).data('w') && $(this).val('');
});
};
})(jQuery);
I’m specifically interested in the following lines:
w && !(w=0) && i.removeClass(css).data('w',0).val('');
and
!i.val() && (w=1) && i.addClass(css).data('w',1).val(text);
Can someone explain this shorthand and rewrite these functions in such a way that I could compare them to better to understand the shorthand myself?
Thank you.
Let’s break each of the statements you’re asking about down to their components:
w– Isw“true”? (checking for!= 0in this case)!(w=0)– Setwto0, take the opposite of the result so the&&chain continuesi.removeClass(css).data('w',0).val('')– Remove the class, set the data to0clear the value.!i.val()– Is the input empty?(w=1)– Setwto1i.addClass(css).data('w',1).val(text);– Add the class, set the data to1and set the text to whatever the watermark text is.Both of these are just statements to really cut down on code, certainly at the expense of readability. If you’re looking at a de-minified version this is very common, if you’re not and this is the original, chase the author with a salad fork, the original should be more more readable than this IMO, though it’s just fine for a minified version.