[go: up one dir, main page]

0% found this document useful (0 votes)
20 views38 pages

Events in Javascript

The document covers JavaScript events, including their types such as mouse, keyboard, form, and touch events. It discusses various event-handling approaches, including inline event handling, event property approach, and the preferred event listener approach. Additionally, it highlights the use of regular expressions for input validation and provides examples of validating user input in forms.

Uploaded by

albsrawys686
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views38 pages

Events in Javascript

The document covers JavaScript events, including their types such as mouse, keyboard, form, and touch events. It discusses various event-handling approaches, including inline event handling, event property approach, and the preferred event listener approach. Additionally, it highlights the use of regular expressions for input validation and provides examples of validating user input in forms.

Uploaded by

albsrawys686
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Events in

JavaScript

Lecture 7
1. Events
2. Event Types
3. Inline Event Handling
Topics Covered 4. Event Property Approach
5. Event Listener Approach

2
Events
• Events are an essential part of almost all real-world
JavaScript programming.
• A JavaScript event is an action that can be detected by
JavaScript.
• We typically describe events in JavaScript as follows:
- we say that an event is triggered,
- then it is handled by JavaScript functions,
- which then do something in response.

3
Event Types: Mouse Events
Event Description

click The mouse was clicked on an element

dblclick The mouse was double clicked on an element

mousedown The mouse was pressed down over an element

mouseup The mouse was released over an element

mouseover The mouse was moved (not clicked) over an element or one of its
child elements.
mouseout The mouse was moved off of an element

mousemove The mouse was moved while over an element

4
Event Types: Keyboard Events

Event Description

keydown A key is pressed.

keypress A key is pressed and released.

keyup A key is released.

5
Event Types: Form Events
Event Description

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).
reset HTML forms have the ability to be reset. This event is triggered when that
happens.
select When the users selects some text. This is often used to try and prevent
copy/paste.
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.

6
Event Types: Touch Events

Event Description

touchstart Triggered when one or more touch points are placed on the touch surface.

touchmove Triggered when one or more touch points are moved along the touch
surface.
touchend Triggered when one or more touch points are removed from the touch
surface.

7
Event-Handling Approaches

• Using hooks to handlers embedded within


markup elements,

• Attaching callbacks to event properties, and

• Using event listeners.

8
Inline Event-Handling

• Handlers for events were specified right in the


HTML markup with hooks to the JavaScript code.

• This approach works but from a software design


standpoint it is far from ideal.

9
Example #1

Here you can see how event handling can be used to


provide feedback to users filling in a registration form.
It will show an error message if their username is too
short.

10
Example #1 : solution

<form method="post" action="http://www.example.org/register">


<label for="username">Create a username: </label>
<input type="text" id="username" onblur="checkUsername()"/>
<div id="feedback"></div>
<label for="password">Create a password: </label>
<input type="password" id="password" /> Event handler
<input type="submit" value="Sign up!" />
</form>
<script src="js/event-attributes.js "></script>

11
Example #1 : solution
js/event-attributes.js

function checkUsername(){
var elMsg = document.getElementById('feedback');
var elUsername = document.getElementById('username');
if (elUsername.value.length < 5) {
elMsg.textContent='Username must be 5 characters or more';
}
}

12
Disadvantages
• The problem with this type of programming is that
the HTML markup and the corresponding
JavaScript logic are woven together.
• It reduces the ability of designers to work separately
from programmers.
• It complicates maintenance of applications.
• It leads to spaghetti coding.

13
Event Property Approach
• The main advantage of this approach is that this code can be
written anywhere, including an external file that helps uncouple
the HTML from the JavaScript.
• However, the one limitation with this approach (and the inline
approach) is that only one handler can respond to any given
element event.

14
Example #2: solution
var elMsg = document.getElementById('feedback');
var elUsername = document.getElementById('username');

function checkUsername(){
if (elUsername.value.length < 5){
elMsg.textContent='Username must be 5 characters or more';
}
}

elUsername.onblur = checkUsername;
No parentheses on
the function name
15
Example #2: shorter solution

var elMsg = document.getElementById('feedback');


var elUsername = document.getElementById('username');

elUsername.onblur = function(){ // OR ()=>


if (elUsername.value.length < 5){
elMsg.textContent='Username must be 5 characters or more';
}
};

16
Event Listener Approach
• Event listeners are a more recent and preferred approach to
handling events.
• They can deal with more than one function at a time.

var myButton = document.getElementById('example');


myButton.addEventListener('click', alert('some message'));
myButton.addEventListener('mouseout', alert('another message'));

• The addEventListener() function is used to register a handler for


the event specified by the first parameter.
• The second parameter of the addEventListener() function is the
handler for the event.
17
Example #3: solution
var elMsg = document.getElementById('feedback');
var elUsername = document.getElementById('username');

function checkUsername(){
if (elUsername.value.length < 5){
elMsg.textContent='Username must be 5 characters or more';
}
}

elUsername.addEventListener(‘blur’, checkUsername);

18
PARAMETERS WITH
EVENT HANDLERS
• If you need to pass arguments to a function that is called by an
event handler or listener, you wrap the function call in an
anonymous function.
• Although the anonymous function has parentheses, it only runs
when the event is triggered.
• The named function can use arguments as it only runs if the
anonymous function is called.

19
PARAMETERS WITH
EVENT HANDLERS
var elUsername = document.getElementById('username') ;
var elMsg = document.getElementById('feedback') ;

function checkUsername(minlength){
if (elUsername.value.length < minlength){
elMsg.textContent = `Username must be ${minlength}
characters or more`;
}
}
elUsername.addEventListener('blur', function(){
checkUsername(5);
});
20
Event Objects
• An event object is automatically passed to event handlers to
provide extra features and information.
• They have properties such as target, which is a reference to the
element the event occurred upon. OR function (event)
Element.addEventListener(“click”, (event)=> {
….
});
• Sometimes, you'll come across a situation where you want to
prevent an event from doing what it does by default such as when
submitting a web form having errors. Thus, we call the
preventDefault() function on the event object.
21
Exercise
Given the following <!DOCTYPE html>
HTML file with a <head>
<meta charset="UTF-8">
paragraph and a <title>JavaScript Event Challenge</title>
button. Add a </head>
<body>
JavaScript code such <h1>JavaScript Event Challenge</h1>
that when you click the <p>Here is a paragraph of text.</p>
<button>Turn Green!</button>
button, it makes the </body>
paragraph turn green. </html>

22
Regular Expression

• Regular expressions are patterns used to match character


combinations in strings.
• Creating regular expressions is done in one of two ways
- Using a regular expression literal enclosed between slashes:
const re = /ab+c/;
- Calling the constructor of the RegExp object:
const re = new RegExp(‘ab+c’);

23
Regular Expression Pattern

. : any single character (except newline) {n} : preceding element exactly n times
[] : single character contained within brackets {n,m} : preceding element at least n and at most m.

[^ ] : single character not contained within brackets {n,} : preceding element at least n.

^ : the starting position in any line \d : digit


$ : the ending position in any line | : OR
? : preceding element zero or one times \s : whitespace character
+ : preceding element one or more times \w : alphanumeric character (A-Z, a-z, 0-9)
* : preceding element zero or more times \ : Escape the special character

24
Regular Expression Pattern

() Groups a subexpression
x(?=y) Lookahead assertion: Matches "x" only if "x" is followed by "y".
x(?!y) Negative lookahead assertion: Matches "x" only if "x" is not followed by "y"
(?<=y)x Lookbehind assertion: Matches "x" only if "x" is preceded by "y".
(?<!y)x Negative lookbehind assertion: Matches "x" only if "x" is not preceded by "y".
?=y Matches any string that is followed by a specific string y
?!y Matches any string that is not followed by a specific string y
25
Common Examples

• /^\d+$/
number
• /^[\s]+/
whitespace at start of line
• /[^@]+@[^@]+/
email
• /^(\d{2}\/\d{2}\/\d{4})|(\d{4}\-\d{2}\-\d{2})$/
date

26
Common Examples

• /^4\d{3}[\s\-]\d{4}[\s\-]\d{4}[\s\-]\d{4}$/
Visa credit card number (four sets of four digits beginning
with the number 4), separated by a space or hyphen.
• /^[a-zA-Z]\w{7,16}$/
password is between 8 and 16 characters starting with lower
or upper case letter
• /\d+(?=\.)/
matches a number only if it is followed by a decimal point.

27
In JavaScript
• Regular expressions are used with RegExp methods such as
test() and String methods: search(), replace() and
match().
let text = "testing: 1, 2, 3"; // Sample text
let pattern = /\d+/; // Matches all instances of one or
more digits
pattern.test(text) // => true: a match exists
text.search(pattern) // => 9: position of first match
text.match(pattern) // => 1: first match
text.replace(pattern, "#") // => "testing: #, 2, 3"

28
Searching With Flags

• Regular expressions can have one or more flags associated


with it such as the flags g and i; the g flag is used to find all
matches within a string rather than just finding the first match.
The i flag specifies that pattern matching should be
case-insensitive. let text = "testing:
• To include a flag with the regular expression: let pattern 1, 2, 3";
= /\d+/g;
const re = /pattern/ flags; text.match(pattern);
=>[“1”, “2”, “3”]
OR text.replace(pattern,‘#‘);
=> "testing: #, #, #"
const re = new RegExp(‘pattern’, ‘flags’);

29
Validating User Input
• Validation is the process of checking whether a value meets
certain rules.
• User input must always be tested for validity.
• Input validation is one of the most common applications of
JavaScript.
• Checking inputs using JavaScript will reduce server load and
increase the perceived speed and responsiveness of the form.
• Common validation activities: email validation, number
validation, and data validation.
• Regular expressions can be used for validation checks.

30
Empty Field Validation

let elform = document.getElementById(“loginForm”);


elform.addEventListener(“submit”, function(e) {
let fieldValue = document.getElementById(“username”).value;
if (fieldValue === null || fieldValue === “” || field.length
=== 0) {
e.preventDefault();
alert(“you must enter a username”);
}
});

31
Non-Text Input Validation
• To ensure that a checkbox, radio buttons or select lists is ticked or
selected, you will have to examine its checked and selected
properties which have true or false.

<input type=“checkbox” name=“save” id=“save” class=“bigCheckB”>

<script>
var rememberMe = document.getElementById(“save”);
if (! rememberMe.checked) {
alert(“Remember me was not checked”);
}
</script>

32
Showing A Password

HTML part
<fieldset>
<legend>Login</legend>
<label for="username">Username: </label>
<input type="text" id="username" name="username" /></br></br>
<label for="pwd">Password :</label>
<input type="password" id="pwd" name="pwd" /></br></br>
<input type="checkbox" id="showPwd">
<label for="showPwd">show password</label>
<input type="submit" value="Login" />
</fieldset>

33
Showing A Password

JavaScript part
var pwd = document.getElementById('pwd');
var chk = document.getElementById('showPwd');
chk.addEventListener('change', function(event){
if (event.target.checked){
pwd.type='text';
}
else{
pwd.type='password';
}
});

34
Validating With RegExp:
Exp #1
HTML part

<form>
<div class="password">
<label for="password" class="required">Password :</label></br>
<input type="password" name="password" id="password" required>
</div>
<div class="password">
<label for="conf-password" class="required">Confirm
password:</label></br>
<input type="password" name="conf-password"
id="conf-password“>
</div>
</form>
35
Validating With RegExp : Exp #1
var pass = document.getElementById("password"); JavaScript part
var pass_conf = document.getElementById("conf-password");
pass.addEventListener('blur', function(){
let pattern = /^[a-zA-Z]\w{7,16}$/;
if (!pattern.test(pass.value)){
alert("Enter a valid password");
}
});
pass_conf.addEventListener('blur', function(){
if(pass.value !== pass_conf.value){
alert("Password is not matched");
}
else{
alert("Password is matched");
}
});

36
Validating With RegExp: Exp #2

HTML part

<form>
<label for="email">Email:</label></br>
<input type="text" id="email“ name="email"/></br></br>
<input type="submit" value="submit"/>
</form>
<p></p>

37
Validating With RegExp: Exp #2

JavaScript part
let elForm = document.querySelector('form');
let elEmail = document.querySelector('#email');
let elpara = document.querySelector('p');
let pattern = /^[^@]+@[^@]+$/;
elForm.addEventListener('submit', function(e){
if(elEmail.value === "" || ! pattern.test(elEmail.value)){
e.preventDefault();
elpara.innerText = "Form is not completed";
}
});

38

You might also like