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>
You should use addEventListener()
instead of onkeypress
addEventListener
allows adding more than a single handler for an event.
document.body.onkeypress = function(e){...}
will override the other function.
<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>
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.