Kundan Sankhe Kundan Sankhe - 2 months ago 8
jQuery Question

jQuery "one" method with if else condition

I'm struggling to implement jQuery's ".one" method with if and else condition. I need to execute this click function only once, whether condition gets true or false.

Please check the below code to simplify my question.



$("span").one("click", function () {
var ind = $("span").index($(this));

if (ind == 0) {
alert ("clicked 1st element");
}

else {
alert ("clicked 2nd element");
}
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>1st click element</span><br>
<span>2nd click element</span>




Answer

In your case you have two span tags. So you attached the event one for both.

The line:

$("span").one("click", function () {

is "equivalent" to the following two lines:

$("span:eq(0)").one("click", function () {
$("span:eq(1)").one("click", function () {

And this is the reason because you receive two events.

If you want to stop the second event and get only the first one you may consider to remove the event handler:

$("span").one("click", function () {
  
  // remove the event for the second span...
  $("span").off("click");
  
  
  var ind = $("span").index($(this));

  if (ind == 0) {
    alert ("clicked 1st element");
  }

  else {
    alert ("clicked 2nd element");
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>


<span>1st click element</span><br>
<span>2nd click element</span>