how to add multiple event handlers to the same event?

时间:2019-03-11 19:50:36

标签: javascript

I'm new to JavaScript and I'm trying to register 2 event handlers to the same event from two different functions, but no matter what I try one event handler overrides the other. Is there any way that I can register multiple event handlers from different functions?

In the code bellow I try to register two event handlers by pressing two buttons, but the handlers override each other.

<p id="text">text</p>

<p id="text1">text1</p>

<button id="myBtn">text</button>

<button id="myBtn1">text1</button>

<script>
document.getElementById("myBtn").addEventListener("click", foo);

document.getElementById("myBtn1").addEventListener("click", bar);

function foo() {
  var target = document.getElementById("text");

  document.body.onkeypress = function(e){
    animateElem(target);
  }
}

function bar() {
  var target = document.getElementById("text1");

  document.body.onkeypress = function(e){
    animateElem(target);
  }
}

function animateElem(elemFound){
    var start = 0.3;
    var increment = 0.3;

    var id = setInterval(allOpacity, 100);

    function allOpacity() {
        if (start > 3) {
          clearInterval(id);
          elemFound.style.opacity = 0.5;
        } 
        else {
          start = start + increment;
          elemFound.style.opacity = start % 1;
        }
    }
}

</script>

1 个答案:

答案 0 :(得分:1)

您应该使用addEventListener()而不是onkeypress

  

addEventListener允许为一个事件添加多个处理程序。

document.body.onkeypress = function(e){...}将覆盖其他功能。

<p id="text">text</p>

<p id="text1">text1</p>

<button id="myBtn">text</button>

<button id="myBtn1">text1</button>

<script>
document.getElementById("myBtn").addEventListener("click", foo);

document.getElementById("myBtn1").addEventListener("click", bar);

function foo() {
  var target = document.getElementById("text");
  document.body.addEventListener('keypress',(e)=>{
    animateElem(target);
  })   
}

function bar() {
  var target = document.getElementById("text1");
  document.body.addEventListener('keypress',(e)=>{
    animateElem(target);
  }) 
}

function animateElem(elemFound){
    var start = 0.3;
    var increment = 0.3;

    var id = setInterval(allOpacity, 100);

    function allOpacity() {
        if (start > 3) {
          clearInterval(id);
          elemFound.style.opacity = 0.5;
        } 
        else {
          start = start + increment;
          elemFound.style.opacity = start % 1;
        }
    }
}

</script>