1 - Jquery (4 Files Merged)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

jQuery

----------
- It is a JavaScript Library.
- Write Less do More
- It comprises pre-defined functions for handling various interactions.
- jQuery is used for
a) DOM Manipulations
b) Validations
c) API Requests
d) Animations and Effects

> npm install jquery --save

- Integrating jQuery with HTML page

<script src="../node_modules/jquery/dist/jquery.js"> </script>

- Invoke [Active] jQuery Library

() - Anonymous function

Syntax:
<script>
$(function(){
--- your jquery code --
})
</script>

(or)
<script>
$(document).ready(function(){
--- your jquery code --
})
</script>

- How jQuery takes control over HTML?


By using CSS selectors

<button> </button> $("button")


<p id="p1"> $("#p1")
<div class="c1"> $(".c1")

- How jQuery handle DOM manipulations


By using jQuery DOM methods.

html() innerHTML
text() innerText
attr() attribute
prop() property
append() to add new element
appendTo() add to specific element
prepend() add as prefix
before() add above
after() add below
val() returns value
each() Iterator

Ex:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Demo</title>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script>
$(function(){
$("#title").html("Welcome to jQuery");
$("p").html("Write Less and Do More.");
$(".sub-title").text("jQuery DOM Methods");
})
</script>
</head>
<body>
<h2 id="title"></h2>
<p></p>
<div class="sub-title"></div>
</body>
</html>

- jQuery Events all are same as JavaScript events


jQuery have clean separation from design.

<button id="btnInsert"> Insert </button>


<input type="text" id="txtName">

$("#btnInsert").click(function(){

})

$("#txtName").keyup(function(){

})

- jQuery events will not allow "this" keyword as argument, you can use
"event".

event : gets event properties


event.target : gets object properties

Syntax:
$("button").click(function(e){
e.clientX
e.clientY
e.target.id
e.target.value
})

Ex:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Demo</title>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script>
$(function(){
$("button").click(function(){
$("#details").html(`
Name : ${$("#Name").val()} <br>
Price: ${$("#Price").val()} <br>
City : ${$("#City").val()} <br>
Stock:
${($("#Stock").prop("checked")==true)?"Available":"Out of Stock"}
`);
})
})
</script>
</head>
<body>
<h2>Register Product</h2>
<dl>
<dt>Name</dt>
<dd><input type="text" id="Name"></dd>
<dt>Price</dt>
<dd><input type="text" id="Price"></dd>
<dt>City</dt>
<dd>
<select id="City">
<option>Delhi</option>
<option>Hyd</option>
</select>
</dd>
<dt>Stock</dt>
<dd><input id="Stock" type="checkbox"> Available</dd>
</dl>
<button>Register</button>
<hr size="4" color="gray">
<p id="details"></p>
</body>
</html>

jQuery Iterations
- for..in
- for..of
- each()

Syntax:
$.each(collection, function(key, value){

})

Ex:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Demo</title>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script>
$(function(){
var categories = ["Electronics", "Footwear", "Fashion"];
$.each(categories, function(key, category){
$(`<li>${category}</li>`).appendTo("ol");
$(`<option
value=${category}>${category}</option>`).appendTo("select");
$(`<tr><td>${category}</td></tr>`).appendTo("tbody");
})
})
</script>
</head>
<body>
<ol></ol>
<select>

</select>
<br><br>
<table border="1" width="200">
<thead>
<tr>
<th>Categories</th>
</tr>
</thead>
<tbody>

</tbody>
</table>
</body>
</html>

Ex: Fakestore API

<!DOCTYPE html>
<html>
<head>
<title>jQuery Demo</title>
<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script>
$(function(){
fetch("http://fakestoreapi.com/products&quot;)
.then(response=>response.json())
.then(data=> {
$.each(data, function(key, product){
$(`
<div class="card m-2 p-2" style="width:200px">
<img src=${product.image} height="150"
class="card-img-top">
<div class="card-header"
style="height:150px">
<p>${product.title}</p>
</div>
<div class="card-footer">
<p>${product.price}</p>
<button class="btn btn-danger w-100">Add
to Cart</button>
</div>
</div>
`).appendTo("#catalog");
})
})
})
</script>
</head>
<body class="container-fluid">
<h2>Products Catalog</h2>
<div class="d-flex justify-content-between flex-wrap" id="catalog">

</div>
</body>
</html>

Ex: Table

<!DOCTYPE html>
<html>
<head>
<title>jQuery Demo</title>
<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script>
$(function(){
fetch("http://fakestoreapi.com/products&quot;)
.then(response=>response.json())
.then(data=> {
$.each(data, function(key, product){
$(`
<tr>
<td>${product.title}</td>
<td><img src=${product.image} width="100"
height="100"></td>
<td>${product.price}</td>
</tr>
`).appendTo("tbody");
})
})
})
</script>
</head>
<body class="container-fluid">
<h2>Products Catalog</h2>
<table class="table table-hover">
<thead>
<tr>
<th>Title</th>
<th>Photo</th>
<th>Price</th>
</tr>
</thead>
<tbody>

</tbody>
</table>
</body>
</html>

jQuery Ajax
jQuery Ajax

- Asynchronous JavaScript And XML


- Ajax is used to handle partial post back.
- It allows to submit only specific portion of page.
- Without reloading complete page you can add new details to page.
- Ajax can fetch, post, modify delete data from API.
- Ajax handles all requests
- Ajax handles CORS. [Cross Origin Resource Sharing]
- Ajax returns JSON.
- jQuery Ajax Methods

$.ajax() : to request any type of data / content


$.getJSON() : only for JSON - GET

Syntax:
$.ajax({
method: GET/ POST,
url: fileName or path,
success: function(){ },
failure: function(){ }
})

Designing SPA Environment:


---------------------------------------
- Single Page Application means, user will stay on only one page and get
access to everything from the page.

Ex:
1. Add a new folder "SPA"
2. Add following files
home.html
electronics.html
footwear.html
fashion.html
index.html

Index.html

<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="../node_modules/bootstrap-
icons/font/bootstrap-icons.css">
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script>
$(function(){
function loadpage(pageName){
$.ajax({
method: "get",
url: pageName,
success : function(data){
$("main").html(data);
}
})
}
loadpage("home.html");
$("#home").click(function(){
loadpage("home.html");
})
$("#electronics").click(function(){
loadpage("electronics.html");
})
$("#footwear").click(function(){
loadpage("footwear.html");
})
$("#fashion").click(function(){
loadpage("fashion.html");
})
$("#products").click(function(){
$("main").html("");
$.ajax({
method: "get",
url: "http://fakestoreapi.com/products&quot;,
success: function(data){
$.each(data,function(key, value){
$(`
<div class="card p-2"
style="width:200px">
<img src=${value.image} class="card-
img-top" height="150">
<div class="card-header">
<p> ${value.title} </p>
</div>
</div>
`).appendTo("main");
})
}
})
})
})
</script>
</head>
<body class="container-fluid">
<header class="bg-danger text-white text-center p-2">
<h2> <span class="bi bi-cart2"></span> Shopping Online</h2>
</header>
<section class="row">
<nav class="col-3">
<div class="mb-2 mt-2">
<button id="home" class="btn btn-danger w-100"> <span
class="bi bi-house"></span> Home</button>
</div>
<div class="mb-2">
<button id="electronics" class="btn btn-danger w-
100"> Electronics </button>
</div>
<div class="mb-2">
<button id="footwear" class="btn btn-danger w-100">
Footwear </button>
</div>
<div class="mb-2">
<button id="fashion" class="btn btn-danger w-100">
Fashion </button>
</div>
<div class="mb-2">
<button id="products" class="btn btn-danger w-100">
All Products </button>
</div>
</nav>
<main class="col-9 d-flex flex-wrap overflow-auto"
style="height: 500px;">

</main>
</section>
</body>
</html>

FAQ: How to write event of element defined in container?


Ans : $(document).on("eventName", "selectorName", function(){

})

Ex:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<link rel="stylesheet"
href="../node_modules/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="../node_modules/bootstrap-
icons/font/bootstrap-icons.css">
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script>
$(function(){
function loadpage(pageName){
$.ajax({
method: "get",
url: pageName,
success : function(data){
$("main").html(data);
}
})
}
loadpage("home.html");
$("#home").click(function(){
loadpage("home.html");
})
$("#electronics").click(function(){
loadpage("electronics.html");
})
$("#footwear").click(function(){
loadpage("footwear.html");
})
$("#fashion").click(function(){
loadpage("fashion.html");
})
$("#products").click(function(){
$("main").html("");
$.ajax({
method: "get",
url: "http://fakestoreapi.com/products&quot;,
success: function(data){
$.each(data,function(key, value){
$(`
<div class="card p-2"
style="width:200px">
<img src=${value.image} class="card-
img-top" height="150">
<div class="card-header"
style="height:180px">
<p> ${value.title} </p>
</div>
<div class="card-footer">
<button value=${value.id}
id="btnCart" class="btn btn-danger w-100"> Add to Cart </button>
</div>
</div>
`).appendTo("main");
})
}
})
})
$(document).on("click","#btnCart",function(e){
alert(e.target.value);
})
})
</script>
</head>
<body class="container-fluid">
<header class="bg-danger text-white text-center p-2">
<h2> <span class="bi bi-cart2"></span> Shopping Online</h2>
</header>
<section class="row">
<nav class="col-3">
<div class="mb-2 mt-2">
<button id="home" class="btn btn-danger w-100"> <span
class="bi bi-house"></span> Home</button>
</div>
<div class="mb-2">
<button id="electronics" class="btn btn-danger w-
100"> Electronics </button>
</div>
<div class="mb-2">
<button id="footwear" class="btn btn-danger w-100">
Footwear </button>
</div>
<div class="mb-2">
<button id="fashion" class="btn btn-danger w-100">
Fashion </button>
</div>
<div class="mb-2">
<button id="products" class="btn btn-danger w-100">
All Products </button>
</div>
</nav>
<main class="col-9 d-flex flex-wrap overflow-auto"
style="height: 500px;">

</main>
</section>
</body>
</html>
Ajax Life Cycle Methods
===================

$.ajax() : It makes a request.

ajaxStart() : It defines actions to perform when request


started.
ajaxSuccess() : It defines that request is success.

ajaxComplete() : It defines the ajax request process completed.

ajaxStop() : It defines that memory is cleaned.

ajaxError() : It catches the problem at every phase.


Error returns various details which include
a) status 404, 200, 302
b) statusText Not Found, OK, Method

Ex:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script>
$(function(){
$("button").click(function(){
$.ajax({
method: "get",
url: "home.html",
success: function(data){
$("div").html(data);
}
})
})
}).ajaxStart(function(){
alert("Your Ajax Request Started");
}).ajaxSuccess(function(){
alert("Ajax request processed successfully..");
}).ajaxComplete(function(){
alert("Response Ready");
}).ajaxStop(function(){
alert("Response sent and memory cleaned");
}).ajaxError(function(e,jxhr){
alert(`Something went wrong\n ${jxhr.statusText}`);
})
</script>
</head>
<body>
<button>Load Page</button>
<div></div>
</body>
</html>

- jQuery DOM
- jQuery Ajax
- jQuery Effects
slide()
fade()
fadeToggle()
slideToggle()
show()
hide()
toggle()
Ex:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script>
$(function(){
$("button").click(function(){
$("div").fadeToggle(2000);
})
})
</script>
</head>
<body>
<button>Show / Hide</button>
<div>
<img src="../public/images/shoe.jpg" width="100"
height="100">
</div>
</body>
</html>

jQuery UI
---------------
- It is similar to bootstrap.
- UI provides jquery related
a) Interactions
b) Components
c) Plugins

Download and Setup jQuery UI for Project


================================
1. Visit the website of "jQuery UI"

https://jqueryui.com/

2. Download "Stable" version

3. Extract the ".zip" folder

4. copy all file and folders and paste into your project
"node_modules"

5. Add into a new folder


"jquery-ui"

jQuery UI - Interactions
--------------------------------
-sortable
-resizable
-draggable
-selectable
Ex:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<link rel="stylesheet" href="../node_modules/jquery-ui/jquery-
ui.css">
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="../node_modules/jquery-ui/jquery-ui.js"></script>
<script>
$(function(){
$("img").resizable();
$("ol").sortable();
})
</script>
</head>
<body>
<img width="100" height="100" src="../public/images/jacket.jpg">
<div>
<ol>
<li>Bootstrap</li>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ol>
</div>
</body>
</html>

jQuery Widgets [Components]


- Accordion
- Buttons
- Dialog
- Calendar etc..

Ex:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<link rel="stylesheet" href="../node_modules/jquery-ui/jquery-
ui.css">
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="../node_modules/jquery-ui/jquery-ui.js"></script>
<script>
$(function(){
$("#menu").menu();
})
</script>
</head>
<body>
<ul id="menu" style="width: 200px;">
<li>Home</li>
<li><div>Electronics</div>
<ul>
<li>TV</li>
<li>
<div>Mobile</div>
<ul>
<li>Samsung</li>
<li>RealMe</li>
</ul>
</li>
<li>Watches</li>
</ul>
</li>
<li>Help</li>
</ul>
</body>
</html>

jQuery Plugins
- Plugin is a 3rd party tool which you can add to your project to make
more effective or to add more functionality.

Grid
Cookies
Cookies
======
- Cookie is a simple text file.
- Client details are stored in cookie, which includes
userid,
password
security details etc..
- You can access and use the data acrross pages.
- Http is a state less protocol. It works with the mechanism
Go-Get-Forget

1. Download and Install any cookie library

> npm install jquery.cookie --save

2. Cookie library commands

$.cookie("cookieName", "value"); create cookies


$.cookie("cookieName"); read cookies value
$.removeCookie("cookieName"); delete the cookie

Ex:
1. Add following pages
- index.html
- login.html
- home.html
- electronics.html

2. index.html

<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<h2>Shopping Online</h2>
<a href="login.html">Login</a>
<span> | </span>
<a href="home.html">Home</a>
</body>
</html>

3. login.html

<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script
src="../node_modules/jquery.cookie/jquery.cookie.js"></script>
<script>
$(function(){
$("button").click(function(){
$.cookie("username",$("#UserName").val());
location.href="home.html";
})
})
</script>
</head>
<body>
<h2>Login</h2>
<dl>
<dt>User Name</dt>
<dd><input type="text" id="UserName"></dd>
<dt>Password</dt>
<dd><input type="password" id="Password"></dd>
</dl>
<button>Login</button>
</body>
</html>

4. home.html

<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script
src="../node_modules/jquery.cookie/jquery.cookie.js"></script>
<script>
$(function(){
if($.cookie("username")==undefined){
location.href = "login.html";
} else {
$("#User").html($.cookie("username"));
}

$("#btnSignout").click(function(){
$.removeCookie("username");
location.href="login.html";
})
})
</script>
</head>
<body>
<h2>Home - <span id="User"></span> <button
id="btnSignout">Signout</button> </h2>
<p>This page is only for authorized users.</p>
<a href="electronics.html">Electronics</a>
</body>
</html>

5. electronics.html

<!DOCTYPE html>
<html>
<head>
<title>Electronics</title>
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script
src="../node_modules/jquery.cookie/jquery.cookie.js"></script>
<script>
$(function(){
if($.cookie("username")==undefined){
location.href = "login.html";
} else {
$("#User").html($.cookie("username"));
}

$("#btnSignout").click(function(){
$.removeCookie("username");
location.href="login.html";
})
})
</script>
</head>
<body>
<h2>Electronics Home <span id="User"></span> <button
id="btnSignout">Signout</button></h2>
<p>Electronics Page..</p>
<a href="home.html">Home</a>
</body>
</html>

Note: Every Cookie life span is until browser opened. You can set expiry
days

$.cookie("cookieName", "value", { expiry : 3 });

jQuery Grid
===========

- Grid allows to present, filter, input, sort data ..


> npm install jsgrid

<!DOCTYPE html>
<html>
<head>
<title>
Grid Demo
</title>
<link rel="stylesheet"
href="../node_modules/jsgrid/dist/jsgrid.css">
<link rel="stylesheet" href="../node_modules/jsgrid/dist/jsgrid-
theme.css">
<script src="../node_modules/jquery/dist/jquery.js"></script>
<script src="../node_modules/jsgrid/dist/jsgrid.js"></script>
<script>
$(function(){
$("table").jsGrid({
width: "100%",
height: "400px",

filtering:true,
editing:true,
sorting:true,
paging: true,

data : [
{"Name":"TV", "Price": 56000.33},
{"Name":"Nike Casuals", "Price": 3200.44}
],

fields : [
{name: "Name", type: "text", width: 150},
{name: "Price", type:"number", width: 150}
]
})
})
</script>
</head>
<body>
<h2>Grid</h2>
<table>

</table>
</body>
</html>

Back End Technologies


- MongoDB
- Node.js
- Express

You might also like