0% found this document useful (0 votes)
32 views12 pages

cs511 Week 7

Uploaded by

ayeshamustafa369
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
32 views12 pages

cs511 Week 7

Uploaded by

ayeshamustafa369
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

Week 7 topic 81

Event handling

In every language of computer science event has its own significance, but in JavaScript, which is
utilized in web development, it is very significant. An event is an action that occurs as a result of
the user or another source, such as a mouse click. Let’s see how it is handled in JavaScript.

Introduction:

 JavaScript event is an action that can be detected by JavaScript.


 Many of them are initiated by user actions, some are generated by the browser itself.
 We say that an event is triggered and then is handled by JavaScript functions.

There are multiple ways to handle an event. Let’s have a look at them.

The given figure no.80.1 depicts it in detail.

Event Handling Approaches-Inline Hook

Figure no.80.1

The very first line portrays that a JavaScript code has been stored in an external file which
includes the some functions such as

function validated (node){….

} // validate the node

function check (node){….

} // check whether the node is or not an appropriate one.

function highlight (node){….

} // highlight text

The figure 80.1 clearly depicts the events on which these functions are invoked.

Another way of handling event is.

Event –Handling Approaches-Event property Approach:


 var mybutton=document.getElementById (‘example’);//In JavaScript, get an element
from the DOM tree (Any approach, such as
query Selector or get element ById, can be used). After that we write function name on
its appropriate event. As shown below.
 myButton.onclick=alert (‘some message’);
 myButon.addEventListener (‘click’, alert (‘some message’));// it take two parameter
 myButton.addEventListner (‘mouseout’, funcName);

Similarly, we may define several events on a single object using this method.

The key benefit of this method is that JavaScript code is segregated from HTML. The script/code
may be in an external file or an embedded JavaScript. The code of HTML will be very clean and
clear, while making changes in HTML you need not worry about the functionality and vice versa.

Another way to define event.

Event-Handling Approach-Event Listener Approach (anon function)// anonymous function


is pass on.

myButton.addEventListener (‘click’, function () {

var d = new Date ();

alert (“You clicked this on” +d.toString ());

}); // in this piece of code the whole function is pass as a parameter to


AddEventListner when a click event is generated.

The last method to handle an event is,

Event Object

When an event is triggered, the browser will construct an event object that contains information
about the event.

div.addEventListener (‘click’, function(e)

//findout where the user clicked

var x=e. clientX;

and via e. Target can be used to manipulate elements of div.

topic 82
apturing and Bubbling.

Let’s see how JavaScript handle events.

Event Handling:


o Events are handled in three phases.
o Capturing

 Event propagation from parent towards the most nested child.


o Target

 Identifying the target.


o Bubbling

 Elements registered for the events are triggered from the most
nested child towards the outermost.

In JavaScript, events progress from the immediate object that caused the event to the document
root. This is referred to as event propagation or event bubbling.

While this may appear to be a difficult concept, the underlying notion is extremely
straightforward. When you click on an element, you're also clicking on all the ascendants in the
DOM tree, as seen in Figure 82.1

Figure 82.1

Week 83
Event Types – mouse, keyboard and touch.

Figure taken from: Fundamentals of Web Development (Second Edition, Pearson), Authors: Randy
Connolly, Ricardo Hoar

The click event is perhaps the most visible, but JavaScript and the DOM support a variety of others. In
reality, the W3C specifies various classes of event, each having multiple types of events inside each class.
Mouse events, keyboard events, touch events, form events, and frame events are some of the most
popular event types.

Let’s have a look at few types of events which are supported by JavaScript.

Mouse Events: Event related to muse is called mouse events.

Mouse events are used to describe a variety of mouse-driven interactions. Mouse click and mouse move
events are two types of mouse events. Many mouse events can be sent at once, which is unusual. The
user may move the mouse from one div to another at the same time, activating the mouseon and
mouseout events as well as the mousemove event. To deal with these difficulties, use the Cancelable
and Bubbles properties. Following is the list of mouse events.

 click The mouse was clicked on an element.


 dblclick The mouse was double clicked on an element. // double click
 mousedown The mouse was pressed down over an element.// pressed button but did not
release yet.
 mouseup The mouse was moved (not clicked) over an element.// when the button is released.
 mouseover The mouse was moved (not clicked) over an element.
 mouseout The mouse was moved off of an element.
 mousemove The mouse was moved while over an element.

These are different types of events which can be used in JavaScript.

Note: click event // in this both up and down will be invoked.

And mouseup is used only for up and likewise mousedown is used only for down.

Keyboard Events: the events related to keyboard is called keyboard events.

Within input fields, these events are most useful. With each key hit, we could, for example, validate an
email address or submit an asynchronous request for a dropdown list of suggestions with each key press.
<input type=“text” id=“key”>

For this input box, we could listen for key press events and replay each pushed key back to the user as
shown below.

document.getElementById(“key”).addEventListener(“keydown”, function (e) {

var keyPressed=e.keyCode;
// get the raw key code

var character=String.fromCharCode(keyPressed);

// convert to string

alert (“Key “ + character + ” was pressed”);

});

Note: Regrettably, different browsers handle keyboard properties differently. For example, the keyCode
property is not available for the keypress event in FireFox. If we used the same callback method for the
keypress event in code above, we'd have to update the code to retrieve the key press as follows:

// use either the which or the keyCode property

var keyPressed = e.which || e.keyCode;

Instead of clogging our code with these kind of browser testing conditional statements, we can use
something like the jQuery framework to handle these quirks.

Types of keyboard events as shown below.

 Keydown The user is pressing a key (this happens first)


 Keypress The user presses a key (this happens after keydown)
 Keyup The user releases a key that was down (this happens last)

Touch events: these are relatively new events which are especially used in mobile devices.

 Touch events are a relatively new category of events that can be triggered by devices with touch
screens.
 The different events (e.g., touchstart, touchmove, and touchend) are analogous to some of the
mouse events (mousedown, mousemove, and mouseup).
 Touch events are only available by default in Chrome and iOS Safari at the time of writing.
 In Edge and FireFox, the user must allow touch events. Pointer events, a new standard
specification that combines mouse, touch screen, and pen input into a single event type, are
supported by Microsoft Edge. However, pointer events are only supported in Edge at the time of
writing.

A form has been created in HTML page, to test a keyboard event.

<form id = “info” method= “post” action= “#”>

<div>

<label> Name</label>
<input type = “text” id = “name”>

</div>

<div>

<label> Email</label>

<input type = “text” id = “ email”>

</div>

<input type = “submit”> </form>

Figure 83.1

//comment out the div that was built with the event listener as shown in figure 83.2

Figure 83.2

<script>

var uname =document. querySelector(‘name’)// reserved word can’t be used as variable.

uname.addEventListener(‘keypress’, function(e){console.log(e.keycode)

if (e.keycode==95)

e.preventdefault();} )

The event listener is working fine, because we get the ASCII code for the keys which are being pressed,
and when the key code is equal to 95 then prevent the default behavior, it implies that the user is not
allowed to type underscore in the input box as shown in figure 83.3,
Week 84

Form Validation; Client side input validation

Form validation is the process of determining whether or not the user has filled out the form correctly.
This activity can be done at various stages. E.g

 HTML Level

// using built-in HTML element we can do validation e.g type of an email address must be email
likewise specify the range for a specific number.

 JavaScript Level

// this is also called client side validation.

Note: the user may disable JavaScript. And submit the form. Because similar situations may arise,
it is vital to validate the form at the server level as well to prevent erroneous data from being
stored in the database. So it good to have validation at all the stages.

 Webserver Level

Form Events:
Events related to form are called form events. Forms are the primary means of collecting and
transmitting user input to the server. Form events allow us to perform some real-time processing in
response to user input. The submit event is the most popular JavaScript listener for forms. We use
preventDefault() to prevent submitting to the server and inform the user if the password field (with id
pw) is blank. Otherwise, nothing is done, allowing the default event to occur (submitting the form).

Catching the submit event and validating a password to not be blank

document.getElementById(“loginForm”).addEventListener('submit', function(e)

{ var pass = document.getElementById(“pw”).value;

if (pass==“”) { alert (“enter a password”);

e.preventDefault (); } });

Form events

 submit// When the form is submitted this event is triggered. We can do some prevalidation of
the

form in JavaScript before sending the data on to the server.

 reset // HTML forms have the ability to be reset. This event is triggered when that happens.
 formdata

Textfield events

 blur // Triggered when a form element has lost focus (that is, control has moved to a different

element), perhaps due to a click or Tab key press.

 change// some <input>, <textarea> or <select> field had their value change. This could mean

the user typed something, or selected a new choice.

 focus // Complementing the blur event, this is triggered when an element gets focus (the user

clicks in the field or tabs to it).

 select // When the users selects some text. This is often used to try and prevent copy/paste.
 ….

Let's look at an example where these events will be used to validate a form.

uname.addEventListener (‘change’, check_name);


email.addEventListener (‘change’, check_email);

form.addEventListener (‘submit’, validate);

function check_name () {

if (this.value.length<5)

this.style= ‘background-color: pink’;

} else {

this.style= ‘background-color: white’;

function check_email () {

var re= / [^@]+@[^\.]+\.[^\.]+/

if (! re.test (this.value)){

This.style= ‘background-color: pink’;

} else {

this.style= ‘background-color: white;

function validate (e) {

var re=/ [^@]+@[^\.]+\.[^\.]+/

if (uname.value.length<5||re.test (email.value) ==false {

e.preventDefault ();

}
Week 85

Introduction to jQuery

JQuery is one of the JavaScript libraries that are used to assist us with web development.

jQuery is a popular framework that gives developers access to cross-browser animation tools, user
interface elements, and DOM manipulation functions, among other things. Learning about frameworks,
especially jQuery, can help you improve your development abilities by allowing you to use ever-evolving
frameworks that provide new and increasingly expected functionality.

The Most popular Framework


 Makes working with JavaScript and DOM easy// JQuery also makes it easy to select an element
and to perform different operation on it
 Cross browser compatibility // it makes sure that the code written is

executable on all the different browsers.

 Most popular JavaScript library (as of 2021). According to w3techs.com


o

 Used by 78% of all website
 96% market share

How to include JQuery in our code, there are multiple ways to include it.

Including JQuey

 Use a Content Delivery Network

(CDN)


o
 <script src = https://code.jquery.com/jquey-3.6.0.min.js> </script>

//can include directly from CDN, min.js is best as it has minimum size.

 Can also be

 Download and used on your web server


 Installed via package manager(npm, yarn, etc)

Note: JQuery can be included in the head, or before body in HTML file.

Let's have a look at an example that how it can be included in HTML file.

Figure 85.1 shows that how it can be included when we have an internet connection.
Figure no 85.1

But if we have no internet connection then download and save it in folder where you have HTML file.

And then include it using absolute path as shown in figure 85.2

Week 86

You might also like