code-8
code-8

Reputation: 58662

How reset the one() function on an object?

I had 6 circles. I'm trying to prevent my users to click NOT in order from 1-6, from left-right.

Ex : Users should not allow clicking on the 2nd or 3rd one if they not yet clicked on the first one.

I have access to the index of all those circles.

if(steps.indexOf(selector) != 0){
    alert("Please start by selecting your device.");
    return false;
}

Since my circles click bind using a one() so it only listening to an event one time only, after they click on a wrong order, my alert pop up, BUT when I click on the same circle again, nothing will happen anymore since the circle bind using one() function.

Is there a way to reset the one() on a $(this) object so that way it will listen to an event again?

$('.' + selector).on("click", function() {
    ...
});

How reset the one() function on an object - jQuery ?

Upvotes: 0

Views: 52

Answers (2)

silentw
silentw

Reputation: 4885

// index of the button that is supposed to be clicked
var curIdx = 0;
// get all the buttons present in the page
const $buttons = document.getElementsByTagName('button');

// iterate all the buttons
for (let idx = 0; idx < $buttons.length; idx++)
{
  // add Event Listener to each button
  $buttons[idx].addEventListener('click', e => {
    // is the index of the button the same as the control var?
    if (idx === curIdx) {
      curIdx++;
      console.log('correct index');
    }
    else
    {
      alert('not the correct index');
    }
  });
}
<div id="app">
  <button id="first">
  First
  </button>
  <button id="second">
   Second
  </button>
   <button id="third">
   Third
  </button>
</div>

Upvotes: 1

eguneys
eguneys

Reputation: 6396

Don't add a one time listener, instead add an all time listener, and solve your problem using business logic. For example like this example:

const $first = document.getElementById('first'),
      $second = document.getElementById('second'),
      $third = document.getElementById('third');
      
      
function makeOrderedClick() {
   let currentStep = 0;
   return index => {
     if (index !== currentStep) {
       alert("Please click step" + currentStep);
       return;
     }
     
     currentStep++;
   };
}

const orderedClick = makeOrderedClick();

$first.addEventListener('click', e => {
  orderedClick(0);
})

$second.addEventListener('click', e => {
  orderedClick(1);
})

$third.addEventListener('click', e => {
  orderedClick(2);
})
<div id="app">
  <button id="first">
  First
  </button>
  <button id="second">
   Second
  </button>
   <button id="third">
   Third
  </button>
</div>

Upvotes: 2

Related Questions