3

<!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!!

3
  • Why you do not write an unique function? Commented Nov 26, 2016 at 16:32
  • @Marielitos i think i too simplify my question, so I ask another question here, if you know the answer plz helping me thanks Commented Nov 26, 2016 at 18:24
  • I think U need change event model. Event capturing <-> Event bubbling. check this web: quirksmode.org/js/events_order.html Commented Jun 1, 2022 at 9:48

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, i think your answer is close, but i think i too simplify my question, so I ask another question here, if you know the answer plz helping me thanks
You cannot count on the order for older browsers. DOM level 2 specified that there were no specification of order. However, with DOM level 3, you CAN count on the order. See stackoverflow.com/questions/2706109/…
1

There are a couple of ways in which you can guarantee the order here:

document.getElementById("abc").addEvenListener("click", function() {
  temp2();
  temp1();
}, false);

Another option would be:

function temp2() {
  alert();
  temp1(); // call temp1 at the end of temp2
}

document.getElementById("abc").addEventListener("click", temp2, false);

1 Comment

i think i too simplify my question, so I ask another question here, if you know the answer plz helping me thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.