JavaScript Primer
JavaScript is the programming language used to add dynamic behavior, store information, and handle requests and responses on a website.
High-level, interpreted programming language, dynamic, weakly typed and prototype-based.
Core technologies of the World Wide Web.
Enables interactive web pages and is an essential part of web applications.
Web browsers have a dedicated JavaScript engine to execute it.
Document method getElementById() method returns an element with a specified value.
Returns null if the element does not exist.
Used when you want to read or edit an HTML element.
Returns an Element object representing the element whose id property matches the specified string.
JavaScript Can Change HTML Content.
One of many JavaScript HTML methods is getElementById().
This example uses the method to "find" an HTML element (with id="demo")
and changes the element content (innerHTML) to "Hello JavaScript":
innerHTML property returns the HTML content (inner HTML) of an element.
Date() function will display date and time at point of execution.
My first javascript
======================================================================
<!DOCTYPE html>
<html>
<body>
<h2>My First JavaScript Example </h2>
<button type="button"
onclick="document.getElementById('javaex').innerHTML = Date()">
Click the button to leverage the javascript Date() function that displays Date and Time.</button>
<p id="javaex"></p>
</body>
</html>
=======================================================================
Next example can change values of an attribute
This resets the value of myImage by loading a different image when the user clicks the buttons related to that image
=======================================================================
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript can display different images?</h2>
<p>Change the myImage value of the src (source) attribute of an image.</p>
<button onclick="document.getElementById('myImage').src='https://storage.googleapis.com/uconnstamford/images/white_husky.png'">Husky with White Background</button>
<img id="myImage" src="" style="width:100px">
<button onclick="document.getElementById('myImage').src='https://storage.googleapis.com/uconnstamford/images/blue_husky.jfif'">Husky with Blue Background</button>
</body>
</html>
==============================================================
External Scripts
Use script src to access external Javascript program and bring into your HTML page
Onclick button will call the script file
========================================================
<!DOCTYPE html>
<html>
<body>
<h2>External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>(myFunction is stored in an external file called "myScript.js")</p>
<script src="https://storage.cloud.google.com/uconn-stamford-web/myScripts.js"></script>
</body>
</html>
===============================================================
myScript.js
========================================================
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
===============================================================
A JavaScript function is a block of JavaScript code that can be executed when "called" for.
For example, a function can be called when an event occurs, like when the user clicks a button.
Variable and operators
=======================================================
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>JavaScript statements are separated by semicolons.</p>
<pre>let a, b, c;
a = 5;
b = 6;
c = a + b;
document.getElementById("demo1").innerHTML = c;</pre>
<p id="demo1"></p>
<script>
let a, b, c;
a = 5;
b = 6;
c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>
</body>
</html>
====================================================
Concatenate two strings together
====================================================
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Operators</h1>
<p>The + operator concatenates (adds) strings.</p>
<pre>var txt1 = "Welcome UCONN Students";
var txt2 = " Stamford RULES";
document.getElementById("demo").innerHTML = txt1 + txt2;
</pre>
<p id="demo"></p>
<script>
var txt1 = "Welcome UCONN Students";
var txt2 = " Stamford RULES";
document.getElementById("demo").innerHTML = txt1 + txt2;
</script>
</body>
</html>
===================================================
Variables are Containers for Storing Data
JavaScript Variables can be declared in 4 ways:
Automatically
Using var Declares a variable
Using let Declares a block variable
Using const Declares a block constant
If - Marks a block of statements to be executed on a condition
For - Marks a block of statements to be executed in a loop
Function - Declares a function
Return - Exits a function
When to Use var, let, or const?
1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you can't use const
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
Names can contain letters, digits, underscores, and dollar signs.
Names must begin with a letter.
Names can also begin with $ and _ (but we will not use it in this tutorial).
Names are case sensitive (y and Y are different variables).
Assignment = assigns values
Addition + adds values
Subtraction - subtract values
Multiplication * multiplies values
Division / divide value
Comparison Operator > compares values
++ increments values
— decrement values
JavaScript has 8 Datatypes
String
Number
Bigint
Boolean
Undefined
Null
Symbol
Object function name(parameter1, parameter2, parameter3) {
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self invoked)
Function parameters
=================================================
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Call a function which performs a calculation and returns the result:</p>
<p> Function takes two values passed as arguments, Muliplies the values and returns the result</p>
<PRE>let x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}</PRE>
<hr>
<p id="demo"></p>
<script>
let x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>
=================================================================
Real Life Objects
In real life, objects are things like: houses, cars, people, animals, or any other subjects.
Here is a car object example:
Car Object
Properties
Methods
car.name = Fiat
car.model = 500
car.weight = 850kg
car.color = white
car.start()
car.drive()
car.brake()
car.stop()
Object Properties
A real life car has properties like weight and color:
car.name = Fiat, car.model = 500, car.weight = 850kg, car.color = white.
Car objects have the same properties, but the values differ from car to car.
Object Methods
A real life car has methods like start and stop:
car.start(), car.drive(), car.brake(), car.stop().
Car objects have the same methods, but the methods are performed at different times.
JavaScript Objects
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to an object named car:
Example
const car = {type:"Fiat", model:"500", color:"white"};
JavaScript Object Definition
How to Define a JavaScript Object
Using an Object Literal
Using the new Keyword
Using an Object Constructor
JavaScript Object Literal
An object literal is a list of name:value pairs inside curly braces {}.
{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}
name:value pairs are also called key:value pairs.
object literals are also called object initializers.
Creating a JavaScript Object
These examples create a JavaScript object with 4 properties:
============================================================
<!DOCTYPE html>
<html>
<body>
<h1>Creating JavaScript Objects</h1>
<h2>Using an Object Literal</h2>
<pre>// Create an Object:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
// Display Data from the Object:
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";</pre>
<hr>
<p id="demo"></p>
<script>
// Create an Object:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
// Display Data from the Object:
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body>
</html>
============================================================
JavaScript can use prompts to allow for user inputs
========================================================
<!DOCTYPE html>
<html>
<body>
<h1>The Window Object</h1>
<h2>The prompt() Method</h2>
<p>Click the button to demonstrate the prompt box.</p>
<pre>function myFunction() {
let person = prompt("Please enter your name");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! Welcome to UCONN";
}</pre>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
let person = prompt("Please enter your name");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! Welcome to UCONN";
}
}
</script>
</body>
</html>
=========================================================
Form validation is extremely important.
Preventing errors from coming into your program
All emails need an @ sign.
Following validate email field.
==================================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Email Signup Form</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h1> Email Validation</h1>
<pre>function validateEmail(email) {
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailPattern.test(email);
}</pre>
<pre>document.getElementById('signupForm').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent the form from submitting
const emailInput = document.getElementById('email');
const errorMessage = document.getElementById('error-message');
if (validateEmail(emailInput.value)) {
errorMessage.textContent = ''; // Clear any previous error message
alert('Email is valid! Form submitted.');
// You can add your form submission logic here
} else {
errorMessage.textContent = 'Please enter a valid email address.';
}
</pre>
<h2>Email Signup Form</h2>
<form id="signupForm">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Sign Up</button>
<p id="error-message" class="error"></p>
</form>
<script>
function validateEmail(email) {
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailPattern.test(email);
}
document.getElementById('signupForm').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent the form from submitting
const emailInput = document.getElementById('email');
const errorMessage = document.getElementById('error-message');
if (validateEmail(emailInput.value)) {
errorMessage.textContent = ''; // Clear any previous error message
alert('Email is valid! Form submitted.');
// You can add your form submission logic here
} else {
errorMessage.textContent = 'Please enter a valid email address.';
}
});
</script>
</body>
</html>
</html>
====================================================
Using Comments to Prevent Execution
Using comments to prevent execution of code is suitable for code testing.
Adding // in front of a code line changes the code lines from an executable line to a comment.
Assignment
= x = y
+= x += y
-= x -= y
*= x *= y
/= x /= y
%= x %= y
**= x **= y
Comparison Operators
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
JSON
JSON, or JavaScript Object Notation, is a data format that's used to store and transmit data in a human-readable and machine-readable way. It's a popular choice for web developers because it's easy to read and understand, and it's independent of any programming language.
Using JSON.stringify()
JavaScript objects can be converted to a string with JSON method JSON.stringify().
JSON.stringify() is included in JavaScript and supported in all major browsers.
================================================
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Objects</h1>
<h2>Display Properties with JSON</h2>
<pre>// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};
// Display JSON
document.getElementById("demo").innerHTML = JSON.stringify(person);</pre>
<p id="demo"></p>
<script>
// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};
// Display JSON
document.getElementById("demo").innerHTML = JSON.stringify(person);
</script>
</body>
</html>
============================================================
Common HTML Events
Here is a list of some common HTML events:
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
====================================================
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Form Example</title>
</head>
<body>
<pre> function validateForm() {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
if (name == "" || email == "") {
alert("Please fill in all fields!");
return false;
}
// You can add more validation logic here
alert("Form submitted successfully!");
}
onclick="validateForm()">Submit
</pre>
<form id="myForm">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br><br>
<button type="button" onclick="validateForm()">Submit</button>
</form>
<script>
function validateForm() {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
if (name == "" || email == "") {
alert("Please fill in all fields!");
return false;
}
// You can add more validation logic here
alert("Form submitted successfully!");
}
</script>
</body>
</html>
====================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date Input Example</title>
</head>
<body>
<h1> Date function Example</h1>
<H2> Use Javascript date function for form validation</H2>
<PRE> // Get the current date
const today = new Date();
// Format the date to YYYY-MM-DD
const formattedDate = today.toISOString().split('T')[0];
// Set the value of the date input to the current date
document.getElementById('date').value = formattedDate;
</PRE>
<form>
<label for="date">Select Date:</label>
<input type="date" id="date" name="date">
<input type="submit" value="Submit">
</form>
<script>
// Get the current date
const today = new Date();
// Format the date to YYYY-MM-DD
const formattedDate = today.toISOString().split('T')[0];
// Set the value of the date input to the current date
document.getElementById('date').value = formattedDate;
</script>
</body>
</html>
No comments:
Post a Comment