I want to know if this is correct.
$('.myfilter').focus(function(){
var length = $(this).val().length;
if (length == 0) {
dosomething
}
}).blur(function(length){
if (length == 0) {
dowhatever
}
})
Above i’ve simplified my code, im just checking if length == 0 on focus and blur for my input. notice how I declared length in focus, but not in blur, but i added the variable name inside .blur(function(length){. Is this the better way to get length accessible in .blur without having to re-declare var length = $(this).val().length; in .blur?
as opposed to this:
$('.myfilter').focus(function(){
var length = $(this).val().length;
if (length == 0) {
dosomething
}
})
$('.myfilter').blur(function(length){
var length = $(this).val().length;
if (length == 0) {
dowhatever
}
})
the first code block is the better way to do this?
How about not declaring any variables at all…
:)Also, this:
Using variables
Usually you want to use a variable if you need to use a certain value multiple times. However, in this case, you need the
this.value.lengthvalue only once (in the if-header). Therefore, you can directly inject this value inside the if-header.$(this) vs this
In order to understand when to use which, you need to understand the difference between a DOM element object and a jQuery object. A jQuery object is a wrapper object which contains zero or more DOM element objects (like an array). It is important to understand that you can only call jQuery methods (like
.addClass()) on jQuery objects, not DOM elements directly.Inside event handler functions, the
thisvalue refers to the DOM element at which the event fired. Now, if you want to call jQuery methods on that DOM element, you need to wrap that DOM element inside a jQuery object – you do this by writing$(this).