简体   繁体   中英

Java Script Add Event Listener

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 :)

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM