Event Handlers <TAG eventHAndler = “JavaScript Code”>
Abort: cancel
Click: click or form element <element onClick=”code/method”></element>
Error: error loading
Focus: web form input
Load:
Mouseout: moves pointer off
Mouseover: moves pointer over
Reset: reste button
select:
submit:
Unload: leaving page
Demo for onClick Event
<p>Demo for onClick Event</p>
<button onclick="GenAlert()">CLick me</button>
<script>
function GenAlert()
{
alert("Welcome to Event in JS");
alert("Function triggered");
}
</script>
Click the button below to display Date
<script>
function dispDate(){
document.getElementById("id1").innerHTML=Date();
}
</script>
<p id="id1">Click the button below to display Date</p>
<button onclick="dispDate()">Click Display date</button>
<button ondblclick="dispDate()">Double Click Display date</button>
Where the page loads you will see an alert message
<div onload="loadFun()">
<p>Where the page loads/reloads you will see an alert message</p>
<script>
function loadFun (){
alert("Page Laoded Successfully")
}
</script>
</div>
Where the page loads you will see an alert message
<div onload="loadImg()">
<p>Where the page loads you will see an alert message</p>
<img src="https://source.unsplash.com/collection/190727/800x600?1" onload="loadImg()">
<script>
function loadImg (){
alert("Image Laoded Successfully")
}
</script>
</div>
Where the page loads you will see an alert message
<div onload="loadImg()">
<p>Where the page loads you will see an alert message</p>
<img src="" onload="loadImg()">
<script>
function loadImg (){
alert("Unable to Laoded image")
}
</script>
</div>
<div>
<div style="background-color: yellow; height:100px; width: 100px;"
onmouseover="mOver()" onmouseout="mOut()">Mouse Enent over/out</div>
<script>
function mOver(){
alert("Mouse over Div");
}
function mOut(){
alert("Mouse out Div");
}
</script>
</div>
<script>
function bigImg(x){
x.style.height="200px";
x.style.width="300px";
}
function smallImg(x){
x.style.height="100px";
x.style.width="150px";
}
</script>
<img src="https://source.unsplash.com/collection/190727/800x600?1"
height="400px" width="600px"
onmouseover="bigImg(this)" onmouseout="smallImg(this)">
Click to count
<p id="count1">Click to count</p>
<button onclick="click1()">click me</button>
<script>
var count = 0;
function click1() {
document.getElementById("count1").innerHTML = count;
return count++;
}
</script>
<script>
function select_fun(){
alert("You cannot select the text");
}
function on_focus(){
document.getElementById("id2").style.backgroundColor="Yellow";
}
</script>
<form action="">
<label> First Name</label>
<input type="text" name="fname" onselect="select_fun()" value="select the words">
<label> Last Name</label>
<input type="text" name="fname" id="id2" onfocus="on_focus()" placeholder="click here">
</form>
<script>
function conToUpper(){
var x=document.getElementById("fname");
x.value=x.value.toUpperCase();
}
function conToLower(){
var x=document.getElementById("lname");
x.value=x.value.toLowerCase();
}
</script>
<form >
<label> First Name in LowerCase</label>
<input type="text" id="fname" onblur="conToUpper()" placeholder="Enter lowercase letter">
<label> Last Name</label>
<input type="text" id="lname" onblur="conToLower()" placeholder="Enter uppercase letter">
</form>
Object
<script>
let user = {
name: "John",
age: 28,
email: "John@gmail.com",
location: "Toronto",
blogs: ["web programming", "HTML"],
logBlogs: function(){
console.log(this.blogs);
document.write(this.blogs);
document.write("<br>");
},
login: function()
{
console.log("The user has logged in")
},
logout: function()
{
console.log("The user has logged out")
}
};
user.login();
user.logBlogs();
console.log(user);
console.log(user.name);
console.log(user["age"]); // Accessing the property by bracket
console.log(user.email);
user.age = 30; // Update
user["name"] = "bob";
user.email = "update@mail.com";
console.log(user.name);
console.log(user.age);
console.log(user.email);
console.log("user type " + typeof(user));
console.log("name type " + typeof(user.name));
console.log("age type " + typeof(user.age));
document.write(user.name);
document.write(user.age);
user.logout();
</script>
Object Prototypes
Object Prototypes
JavaScript objects inherit features from one another using Prototypes.
Each and every object
features a
prototype
object that functions as a template from which it
inherits methods and properties. Such objects may also contain their own
prototype
objects from which they also inherit
various methods and properties…and so on. This chain of inheritance is
called the prototype chain.
<p id="output"></p>
<script>
var output = document.getElementById('output');
/* STEP 1: Create an object (looks a lot like declaring a variable, but with empty braces), then open this page in a browser and enter 'Coffee' in the console */
function Coffee(size, isDecaf, qtyCream, qtySugar)
{
this.size = size;
this.isDecaf =isDecaf;
this.qtyCream=qtyCream;
this.qtySugar=qtySugar;
this.decaf=(this.isDecaf === true ? "decaffinated" : "");
this.decription =function(){
output.innerHTML="A "+this.size+this.decaf+" coffee with "+this.qtyCream+" cream and "+this.qtySugar+" sugar.";
}
}
/* STEP 2: Instatiate a coffee based on the above constructor function */
let scottscoffee = new Coffee("extra large", false, 2,1)
/* STEP 3: Refresh the page, and in the console, begin to call a method on scottsCoffee by typing 'scottsCoffee.' - look at all the members and methods */
scottscoffee.decription();
/* STEP 4: Enter into the console, scottsCoffee.valueOf() and look at the result. scottsCoffee doesn't have such a method, and neither does the constructor function, 'Coffee'. But the 'Object' object does - so through inheritance, scottsCoffee has access to the method, valueOf(). */
/* STEP 5a: Each object has a prototype member that isn't really directly accessible, but it can be referenced using the deprecated '__proto__' - using a double underscore on either side of the word 'proto'. Try it - scottsCoffee.__proto__.__proto__ */
/* STEP 5b: The more modern way to do this is … Object.getPrototypeOf(scottsCoffee) - try THIS in the console */
/* STEP 5c: EVERYTHING is an object in JavaScript. Try accessing the prototype property of Coffee (which even though it is a constructor function it is still an object) with Coffee.prototype in the console. Then try Object.Prototype */
/* STEP 6a: Let's circle back to create() - use scottsCoffee to create a new object instance - one based on scottsCoffee. */
let megansCoffee = Object.create(scottscoffee);
megansCoffee.size ="small";
megansCoffee.isDecaf=true;
megansCoffee.qtyCream=1;
megansCoffee.qtySugar=2;
/* STEP 6b: See how this new object inherits from the prototype with richsCoffee.__proto__ in the console. */
/* STEP 7a: Each constructor function includes a prototype property with a value equal to an object that contains a constructor property. Try it out by typing scottsCoffee.constructor and richsCoffee.constructor */
let lukesCoffee = new megansCoffee.constructor("medium",false,1,1);
/* STEP 7b: Since constructor is also a function, you can use it to create a new object instance - try it! */
/* STEP 7c: Attempt via the console to access the new object's properties - kathysCoffee.size, kathysCoffee.isDecaf, etc. */
/* STEP 7d: Now see if the new object can access the description() method… */
/* STEP 7e: The constructor has other features - try using it to discover the name of an instance's constructor by typing kathysCoffee.constructor.name into the console. */
/* STEP 8a: We can modify the prototype property of a constructor function - let's add another method to Coffee */
Coffee.prototype.thanks=function()
{
output.innerHTML="Thanks for a great "+this.size+" coffee"
}
// What's really interesting about the above code is that every instance based on the Coffee constructor has been updated due to prototypical inheritance!
/* STEP 8b: Now let's call up this method on one or more of our Coffee instances from the console (scottsCoffee, richsCoffee, or kathysCoffee). */
lukesCoffee.thanks();
// Next, open up coffee.html and we will put prototypical inheritance to work.
// This page inspired by and adapted from https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes
// Special thanks to https://openclipart.org/detail/293550/coffee-to-go for the very cool coffee cup SVG
</script>
Inheritance in JavaScript
Let’s put JavaScript prototypes and inheritance to work – with coffee.
<div>
<h1>Inheritance in JavaScript</h1>
<p>
Let's put JavaScript prototypes and inheritance to work – with
<em>coffee</em>.
</p>
<p id="output"></p>
<script defer>
var output = document.querySelector('#output');
class Coffee
{
size;
isDecaf;
constructor(size,isDecaf){
this.size=size;
this.isDecaf=isDecaf;
};
serveIt()
{
//Create an image of the coffee ordered
const cup = document.createElement("img")
//Set the src for image
let cupImage="http://keishoseiho.com/wp-content/uploads/2024/03/coffee-cup.svg";
//Determine caffeine status
let decaf;
if (this.isDecaf === true) {
decaf="decaffinated";
cupImage="http://keishoseiho.com/wp-content/uploads/2024/03/coffee-cup-green.svg";
}else{
decaf="caffeinated";
}
//Set the src attribute
cup.setAttribute("src", cupImage);
//Set the size of the cup SVG image based on this.size
let cupSize;
switch (this.size) {
case "small":
cupSize="100px";
break;
case "medium":
cupSize="125px";
break;
case "large":
cupSize="150px";
break;
default:
cupSize="100px";
}
//Size the IMG in terms of height
cup.setAttribute("height", cupSize);
//Generate the description
let description=`A ${this.size} ${decaf} coffee`;
cup.setAttribute("title", description);
//Insert the new IMG element into the paragraph
output.appendChild(cup);
//Output all the object member values
for (const [key, value] of Object.entries(this))
{
console.log(`${key} ${value}`);
};
};
};
/* STEP 2a: Instatiate a coffee based on the above constructor function */
let scottsCoffee= new Coffee("large", false);
/* STEP 2b: Call up the serveIt() method */
scottsCoffee.serveIt();
//Creating a subclass for Coffee class
class Latte extends Coffee{
milkType;
constructor(size, isDecaf, milkType){
super(size, isDecaf);
this.milkType=milkType
};
latteDesc(){
console.log(`A ${this.size} latte with steamed ${this.milkType} milk`)
};
};
//Create an instance for Latte object
scottsCoffee=new Latte("medium", true, "almond");
//Call the latte description method
scottsCoffee.serveIt();
scottsCoffee.latteDesc();
</script>
</div>
RELATED POSTS
View all