.is() jQuery - how does it work?

Asked

Viewed 478 times

2

How the function works. is() in jQuery, I saw it being used in a code, the code has a variable $lastClicked, declared, then a comparison is made (!$(this).is($lastClicked)), only that I didn’t understand how . is() works, and what is the purpose of $lastClicked in code! if anyone can answer - thank you.

The code is as follows::

// Apenas parte do código ...
$(function(){
    var $lastClicked;
    function onTarefaItemClick(){
        if(!$(this).is($lastClicked)){
            if($lastClicked !== undefined){
                savePendingEdition($lastClicked);
            }
            $lastClicked = $(this);
            var text = $lastClicked.children('.tarefa-texto').text();
            var html = '<input type="text" class="tarefa-edit" value="' + text + '">';
            $lastClicked.html(html);
            $('.tarefa-edit').keydown(onTarefaEditKeydown);
        }
    }
    $('.tarefa-item').click(onTarefaItemClick);
    function onTarefaEditKeydown(event){
        if(event.which === 13){
            savePendingEdition($lastClicked);
            $lastClicked = undefined;
        }
    }
});

3 answers

4

The function is() of jQuery is used to check if an object "matches" with a given selector.

Take this example:

console.log("O elemento 'i' é um input: " + $('#i').is('input'));
console.log("O elemento 'i' é um input text: " + $('#i').is('input[type=text]'));
console.log("O elemento 'i' é um input radio: " + $('#i').is('input[type=radio]'));

console.log("O elemento 'c' é um input: " + $('#c').is('input'));
console.log("O elemento 'c' é um input text: " + $('#c').is('input[type=text]'));
console.log("O elemento 'c' é um input checkbox: " + $('#c').is('input[type=checkbox]'));
console.log("O elemento 'c' é um input checkbox e está checado: " + $('#c').is('input[type=checkbox]:checked'));
console.log("O elemento 'c' é um input checkbox e não está checado: " + !$('#c').is('input[type=checkbox]:checked'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="i" type="text" />
<input id="c" type="checkbox" />

In the example, the is() is used to compare the element with multiple selectors, checking whether the element "matches" with each of them, if is as one of the selectors.

To clarify the question code example, the purpose is probably to know whether or not the element that was clicked is the same that was previously clicked. See that the variable $lastClicked or is set as undefined, with $(this), i.e., some element clicked. At the beginning of Function, it checks if(!$(this).is($lastClicked)), that is, if the element clicked (this) is not the last element that clicked earlier ($lastClicked).

4


The is Jquery is used to check whether the selected element corresponds to a particular element.

This function can be called by passing different parameters:

  • Selector
  • Object
  • Function

Passing a dial

When a dial passes the is checks if the element you have matches the selector passed. A simple example of this would be $(this).is(".premiado") checking whether the current element, the $(this) corresponds to the class premiado. It is important to mention that the selector can be much more elaborate including all types of selectors supported in both Jquery and CSS3.

Example of is based on a class:

$("li").on("click", function(){
  if ($(this).is(".premiado")){
    console.log("li premiado!"); 
  }
  else {
    console.log("li normal");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Clique nos vários li's
<ul>
  <li>1</li>
  <li>2</li>
  <li class="premiado">3 (premiado)</li>
  <li>4</li>
  <li>5</li>
 </ul>

Passing an Object

It is also possible to check if one element corresponds to another you have stored in an object. This general rule implies that you previously saved an element with something like let elemento = $(this); and then further to the forehead if it matches doing $(...).is(elemento).

With the passage of an object it is easy to assemble an example that tells you whether you clicked on the last element or on a different one:

let ultimo;
$("li").on("click", function(){
  if ($(this).is(ultimo)){
    console.log("li é o mesmo que o anterior"); 
  }
  else {
    console.log("li diferente");
  }
  ultimo = $(this); //o ultimo passa a ser este elemento
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Clique nos vários li's, e mais que uma vez no mesmo
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
 </ul>

Passing Function

Although much less common it is also possible to pass a function that tells you whether or not it corresponds to the element. The corresponding is done through what the function returns, being that true does the is match and false does not match. In this function you can implement any logic you want.

Usually this form takes the following shape:

if ($(this).is(function(){
    //função para avaliar se é ou não retornando um booleano
}){
    //código para executar quando é   
}

Example of a is that checks if the clicked element matches one that has a specific text:

$("li").on("click", function(){
  if ($(this).is(function(){
    return $(this).text() == "5";
  })){
    console.log("li com texto 5"); 
  }
  else {
    console.log("li com texto diferente de 5");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Clique nos vários li's
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
 </ul>

In this case you can also use a Arrow Function to simplify the function code, transforming it into:

if ($(this).is(() => $(this).text() == "5"){
    console.log("li com texto 5"); 
}

Code shown in question

If you look at the code that you have in the question and my example of passing an object you will see that it is the same. The code that checks if the clicked element is different from the last one that was clicked:

if(!$(this).is($lastClicked)){

Will do various things and save the last clicked as the current:

$lastClicked = $(this);

Also stores changes if there is a last one (first click has no last):

if($lastClicked !== undefined){
    savePendingEdition($lastClicked);

0

Another view is that what . is() does is check that the checked object $("x") matches the given . is("y") selector, returning a boolean.

In practice I use it only to check states of the elements, examples:

Check if a div is hidden:

var divEstaOculta = $("#minhDiv").is(":hidden"); 

Check if an input is disabled:

var estaDesabilitado = $("#meuInput").is(":disabled");

Check if a checkbox is checked:

var estaCheckado = $("#meuCheckbox").is(":checked");

But it is also returned true, when you compare with some object property, example:

<div id="meuId" class="minhaClasse" ></div>

$("#meuId").is(".minhaClasse") // true

Browser other questions tagged

You are not signed in. Login or sign up in order to post.