Sunday, 30 September 2018

JavaScript: Event handling

JavaScript provides very good support for event handling like mouse clicks, keyboard clicks etc., in simple terms, you registers a function on specific event. Whenever that event happens, the registered function executes the code.

How to assign an event handler to an element
There are many ways to assign event handler to an element.
a.   As an attribute in html tag
b.   Using a DOM-object property

As an attribute in html tag
<input type="button" onclick="goodMorning();" value="Good Morning" />

As you see above statement, Whenever you click the button onClick, it calls the function goodMorning().

Following is the complete working application.

process.js
function goodMorning(){
 alert("Good Morning");
}

function goodAfternoon(){
 alert("Good Afternoon");
}

function goodNight(){
 alert("Good Night");
}


events.html
<!DOCTYPE html>

<html>

<head>
    <title>Accessing style properties</title>
    <script src="process.js"></script>
</head>

<body>
    <input type="button" onclick="goodMorning();" value="Good Morning" />
    <input type="button" onclick="goodAfternoon();" value="Good Afternoon" />
    <input type="button" onclick="goodNight();" value="Good Night" />
</body>

</html>


Using a DOM-object property
document.getElementById("morning").onclick = goodMorning;

Above statement gets an element with if ‘morning’ and calls the function goodMorning when mouse clicks on it.

process.js

function goodMorning(){
 alert("Good Morning");
}

function goodAfternoon(){
 alert("Good Afternoon");
}

function goodNight(){
 alert("Good Night");
}

function initEvents(){
 document.getElementById("morning").onclick = goodMorning;
 document.getElementById("afternoon").onclick = goodAfternoon;
 document.getElementById("night").onclick = goodNight;
}

window.onload = initEvents;


events.html

<!DOCTYPE html>

<html>

<head>
    <title>Accessing style properties</title>
    <script src="process.js"></script>
</head>

<body>
    <input type="button" id="morning" value="Good Morning" />
    <input type="button" id="afternoon" value="Good Afternoon" />
    <input type="button" id="night" value="Good Night" />
</body>

</html>



Previous                                                 Next                                                 Home

No comments:

Post a Comment