0

Im trying to attach an event listener but instead of an event such as 'click' I want it to be when a variable meets a certain criteria. For example:

let x = 1;
let y = 2;

const myObject = document.getElementById('myObject')

myObject.addEventListener('x==3 && y == 4', function() {
}

I'm not sure if this is possible or not without using the if statement within the function but maybe you guys had a solution or a way to work around that ? Thanks in Advance :)

2
  • Is the myObject a input? Commented Jun 10, 2018 at 16:52
  • So you want to trigger a function as soon as the variables change and meet a specific condition? That’s not event listeners, that would be observable objects. Don’t use variables, use an object with x and y as properties and wrap them in a Proxy, then you can change those properties whenever you want and each time they are changed, you can run a function. If you just want to check the condition upon clicking, then just use the click event with the if statement. Commented Jun 10, 2018 at 17:15

1 Answer 1

1

I'm not sure how your myObject element knows what the values of x and y are, but you can add event listeners to the id of some element that causes the change to x or y, and run a function that checks their values. If you want to trigger an entirely different event when x and y hit the desired values, just call a function inside the if statement that checks for the values you want. This example resets the values if either x or y reach 10. Hope this is helpful in some way!

const xElem = document.getElementById('x');
const yElem = document.getElementById('y');
let x = 0;
let y = 0;

xElem.addEventListener('click', changeFunction);
yElem.addEventListener('click', changeFunction);

function changeX(){
  x++;
  xElem.innerHTML = `x = ${x}`;
}

function changeY(){
  y++;
  yElem.innerHTML = `y = ${y}`;
}

function changeFunction() {
  if(x == 3 && y == 4){
    alert('there you have it!');
  }
  if(x == 10 || y == 10){
    doThisOtherThing()
  }
}

function doThisOtherThing() {
  alert('reset');
  x = 0;
  y = 0;
  xElem.innerHTML = 'change x';
  yElem.innerHTML = 'change y';
}
<div>
  <button id="x" onClick="changeX()">change x</button>
  <button id="y" onClick="changeY()">change y</button>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.