简体   繁体   中英

Javascript to trigger one function only if two events are both true

Say I want to activate myFunction only if the user has pressed the paragraph with a key and clicks on it. In the case below, the function will get triggered if any of the events is true.

<p id="p1" onClick="myFunction()" onKeyDown="myFunction()">
Text awaiting to be colored in red</p>

<script>
    function myFunction(){
        document.getElementById("p1").style.color = "red";
    }
</script>

You need one extra variable isKeyDown, and isKeyDown should be set to true on keydown, and set to false on keyup.

And than in click callback check is isKeyDown true, call myFunction.

You'll need to breakdown into two methods. First is keystrokes->click and then click->keystrokes. I'm not sure if this is achievable on pure/vanilla javascaript. But on jquery it goes something like:

$('#p1' ).keydown(function() {
  if($('#p1').click()) {
    document.getElementById("p1").style.color = "red";
  }
});

$('#p1')click(function () {
  if($('#p1').keydown()) {
    document.getElementById("p1").style.color = "red"; 
  }
 });

An example of how you could do it. This works with Enter and normally clicking it. Really you don't need to make p focus but I thought it was neat, even though you can still handle the key events from the document and since the click only registers on p there's nothing to worry about.

 var p = document.getElementById('p1'); p.addEventListener('mousedown', function(e) { p.clicked = true; checkEvents(p); }); p.addEventListener('mouseup', function(e) { p.clicked = false; }); p.addEventListener('keydown', function(e) { if (e.keyCode === 13) { p.enterDown = true; } }); p.addEventListener('keyup', function(e) { checkEvents(p); if (e.keyCode === 13) { p.enterDown = false; } }); function checkEvents(el){ if(el.enterDown && el.clicked){ el.style.backgroundColor = 'red'; } } 
 p:focus { outline: none; } 
 <p id="p1" tabindex='0'> Text awaiting to be colored in red</p> 

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