chenyuxian chenyuxian - 7 days ago 10
HTML Question

How to change event execution order?



<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Close window</title>
</head>
<body>
<button id="abc" onclick="temp1()">button</button>

<script type="text/javascript">
function temp1() {
alert("temp1");
};

function temp2() {
alert("temp2");
}

document.getElementById("abc").addEventListener("click", temp2, false);
</script>
</body>
</html>





but I want to show "temp2" first, and then show "temp1"

Is that possible? or the event execution order depends on the browser so I can't change it?

thanks for help!!

Answer

Please review this one:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Close window</title>
</head>

<body>
  <!-- here is your first AddEventlistener-->
  <button id="abc" onclick="temp1()">button</button>

  <script type="text/javascript">
    function temp1() {
      alert("temp1");
    };

    function temp2() {
      alert("temp2");
    }

    /*then here is your second AddEventlistener*/
    var d = document.getElementById("abc");
    d.addEventListener("click", temp2, false);

    /*javascript will execute it in order
      if you want to change the order. remove first EventListener then register new one after. something like this:
    */
     //remove listener
    d.onclick = null;
     //register new
    d.addEventListener('click', temp1);
  </script>
</body>

</html>

Comments