Events in Javascript
Events in Javascript
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
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
4
Event Types: Keyboard Events
Event Description
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
8
Inline Event-Handling
9
Example #1
10
Example #1 : solution
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
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.
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
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.
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
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
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.
<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