Attaching Events - Exercise

Contact Us or call 1-877-932-8228
Attaching Events - Exercise

Attaching Events

Duration: 10 to 20 minutes.

In this exercise you will use the observeEvent() function to attach multiple callback functions to the same event.

  1. Open HTMLDOM/Exercises/AttachEvent.html for editing. A screen shot of the page is shown below:Screenshot of Page
  2. In the init() function, write code so that...
    • when addButton is clicked the addNumbers() function is called.
    • when subtractButton is clicked the subtractNumbers() function is called.
    • when either button is clicked the incrementProblems() function is called.
  3. To test your solution, open HTMLDOM/Exercises/AttachEvent.html in your browser.
    • When you click on the plus button, it should add the two numbers and increment the number of problems shown by one.
    • When you click on the minus button, it should subtract the number 1 from number 2 and increment the number of problems shown by one.

Code Sample:

HTMLDOM/Exercises/AttachEvent.html
---- C O D E   O M I T T E D ----

	observeEvent(window,"load",init);
	function init() {
		var addButton = document.getElementById("addButton");
		var subtractButton = document.getElementById("subtractButton");

		/*
			Write code so that...
				- when addButton is clicked the addNumbers() function is called
				- when subtractButton is clicked the subtractNumbers() function is called
				- when either button is clicked the incrementProblems() function is called
		*/
	}

	function addNumbers(e) {
		e = e || window.event;
		var target = e.target || e.srcElement;
		var num1 = target.form.num1.value;
		var num2 = target.form.num2.value;
		var result = Number(num1) + Number(num2);
		target.form.result.value = result;
	}

	function subtractNumbers(e) {
		e = e || window.event;
		var target = e.target || e.srcElement;
		var num1 = target.form.num1.value;
		var num2 = target.form.num2.value;
		var result = num1 - num2;
		target.form.result.value = result;
	}

	var numProbs=0;
	function incrementProblems() {
		numProbs++;
		document.getElementById("numProblems").innerHTML = numProbs;
	}
---- C O D E   O M I T T E D ----

Solution:

HTMLDOM/Solutions/AttachEvent.html
---- C O D E   O M I T T E D ----

function init() {
	var addButton = document.getElementById("addButton");
	var subtractButton = document.getElementById("subtractButton");
	observeEvent(addButton,"click",addNumbers);
	observeEvent(subtractButton,"click",subtractNumbers);
	observeEvent(addButton,"click",incrementProblems);
	observeEvent(subtractButton,"click",incrementProblems);
}
---- C O D E   O M I T T E D ----
Next