Unit IV
Unit IV
JavaScript
JavaScript Events-Modifying CSS of Elements using JavaScript -JavaScript
Classes-Introduction to JQuery-JQuery Selectors-Using JQuery to add
interactivity-JQuery Events-Modifying CSS with JQuery -Adding and
Removing elements with JQuery-AJAX with JQuery - Animations with
JQuery(hide,show,animate,fade methods,slide methods)
JavaScript Events:
The change in the state of an object is known as an Event. In html, there are various
events which represent that some activity is performed by the user or by the
browser. When javascript code is included in HTML, js react over these events and
allow the execution. This process of reacting over the events is called Event
Handling. Thus, js handles the HTML events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute
the task to be performed on the event.
Mouse events:
Keyboard events:
Keydown & Onkeydow & When the user press and then release the
Keyup onkeyup key
Form events:
Window/Document events :
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the
browser unloads it
Click Event :
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write("This is JavaTpoint");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>
Output:
MouseOver Event :
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is JavaTpoint");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
Output:
Focus Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
//-->
</script>
</body>
</html>
Output:
Keydown Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
Output:
Load event :
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>
Output:
JavaScript addEventListener() :
The addEventListener() method is used to attach an event handler to a particular
element. It does not override the existing event handlers. Events are said to be an
essential part of JavaScript. A web page responds according to the event that
occurred. Events can be user-generated or generated by API's. An event listener is
a JavaScript's procedure that waits for the occurrence of an event.
Syntax :
CODE:
<!DOCTYPE html>
<html>
<body>
<p id = "para"></p>
<script>
document.getElementById("btn").addEventListener("click", fun);
function fun() {
document.getElementById("para").innerHTML = "Hello World" + "<br>" +
"Welcome to the javaTpoint.com";
</script>
</body>
</html>
Output:
So, in Bubbling, the event of the paragraph element is handled first, and then the
div element's event is handled. It means that in bubbling, the inner element's event
is handled first, and then the outermost element's event will be handled.
In Capturing the event of the div element is handled first, and then the paragraph
element's event is handled. It means that in capturing the outer element's event is
handled first, and then the innermost element's event will be handled.
We can specify the propagation using the useCapture parameter. When it is set to
false (which is its default value), then the event uses bubbling propagation, and
when it is set to true, there is the capturing propagation.
CODE:
<!DOCTYPE html>
<html>
<head>
<style>
div{
background-color: lightblue;
border: 2px solid red;
font-size: 25px;
text-align: center;
}
span{
border: 2px solid blue;
}
</style>
</head>
<body>
<h1> Bubbling </h1>
<div id = "d1">
This is a div element.
<br><br>
<span id = "s1"> This is a span element. </span>
</div>
<h1> Capturing </h1>
<div id = "d2"> This is a div element.
<br><br>
<span id = "s2"> This is a span element. </span>
</div>
<script>
document.getElementById("d1").addEventListener("dblclick", function()
{alert('You have double clicked on div element')}, false);
document.getElementById("s1").addEventListener("dblclick", function()
{alert('You have double clicked on span element')}, false);
document.getElementById("d2").addEventListener("dblclick", function()
{alert('You have double clicked on div element')}, true);
document.getElementById("s2").addEventListener("dblclick", function()
{alert('You have double clicked on span element')}, true);
</script>
</body>
</html>
Output:
Example :
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>
Using Events:
The HTML DOM allows you to execute code when an event occurs.
Events are generated by the browser when "things happen" to HTML elements:
● An element is clicked on
● The page has loaded
● Input fields are changed
You will learn more about events in the next chapter of this tutorial.
This example changes the style of the HTML element with id="id1", when the user
clicks a button:
Example:
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
JavaScript Classes
Syntax
class ClassName {
constructor()
{ ... }
}
Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
● HTML/DOM manipulation
● CSS manipulation
● HTML event methods
● Effects and animations
● AJAX
● Utilities
There are several ways to start using jQuery on your web site. You can:
● Production version - this is for your live website because it has been
minified and compressed
● Development version - this is for testing and development (uncompressed
and readable code)
The jQuery library is a single JavaScript file, and you reference it with the HTML
<script> tag (notice that the <script> tag should be inside the <head> section):
<head>
<script src="jquery-3.6.1.min.js"></script>
</head>
jQuery CDN:
If you don't want to download and host jQuery yourself, you can include it from a
CDN (Content Delivery Network).
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js">
</script>
</head>
jQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s).
jQuery selectors are used to "find" (or select) HTML elements based on their
name, id, classes, types, attributes, values of attributes and much more. It's based
on the existing CSS Selectors, and in addition, it has some custom selectors.All
selectors in jQuery start with the dollar sign and parentheses: $().
$("p")
Example:
When a user clicks on a button, all <p> elements will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
The #id Selector:
The jQuery #id selector uses the id attribute of an HTML tag to find the specific
element.
An id should be unique within a page, so you should use the #id selector when
you want to find a single, unique element.
To find an element with a specific id, write a hash character, followed by the id of
the HTML element:
$("#test")
Example:
When a user clicks on a button, the element with id="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
To find elements with a specific class, write a period character, followed by the
name of the class:
$(".test")
Example:
When a user clicks on a button, the elements with class="test" will be hidden:
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
$("ul li:first") Selects the first <li> element of the first <ul>
$("a[target='_blank'] Selects all <a> elements with a target attribute value equal to
") "_blank"
$("a[target!='_blank' Selects all <a> elements with a target attribute value NOT
]") equal to "_blank"
$(":button") Selects all <button> elements and <input> elements of
type="button"
<button>This is a button.</button>
This is a button.
In order to make the button do something other than sit there, we have to give it
a behavior with jQuery. Here’s what that looks like:
But whoa, that’s a lot of stuff! A lot of strange parentheses and quotes and
brackets and who knows what else. Here’s the code from inside the <script> tag
again—this time with the lines numbered and the “movable” parts (i.e., you can
swap out) highlighted in bold.
1 $(function() {
2 $(".clickme").on("click", function() {
3 alert("Good job!");
4 });
5 });
Hiding elements :
So we’re well on our way to making our pages interactive. But making a little
dialog window appear doesn’t seem very useful. Preferably we’d like to make it so
user action results in some kind of change happening on the page itself.
Well, it so happens that this is easy to do! The first thing we’re going to learn how
to do is to reveal and hide elements in response to the user clicking a button. In
the following example, the paragraph tag will disappear when the user clicks the
button.
$(".hideme").hide();
This line tells jQuery to find all elements on the page with the hideme class and…
hide them. (Behind the scenes, jQuery “hides” the elements by setting their
display properties to none.) If you wanted the event to hide elements belonging
to a different class, you could change the string hideme to something else.
The string hide has no inherent meaning; it’s just one of the many special words
that jQuery understands. You would only know that hide does what it does if
you’d read its documentation. Learning jQuery is all about learning all of the
different things we can put where the word hide is in this example, and what
those things do. (The full list is here, but you might be most interested in jQuery
effects.)
Revealing elements :
What’s good for the goose is good for the gander, and likewise it’s possible to
reveal previously hidden elements, using code very similar to the example above.
Here’s how:
$(".telljoke").show()
This time, we’re using jQuery’s show function, which causes all elements
belonging to the class in the parentheses before it to be displayed (if they weren’t
already displayed).
jQuery Events
jQuery events are the actions that can be detected by your web application. They
are used to create dynamic web pages. An event shows the exact moment when
something happens.
● A mouse click
● An HTML form submission
● A web page loading
● A keystroke on the keyboard
● Scrolling of the web page etc.
Window Events
$("p").click();
The next step is to define what should happen when the event fires. You must pass
a function to the event:
$("p").click(function(){
// action goes here!!
});
Commonly Used jQuery Event Methods:
$(document).ready()
click()
The function is executed when the user clicks on the HTML element.
The following example says: When a click event fires on a <p> element; hide the
current <p> element:
Example :
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<p>Click me away!</p>
<p>Click me too!</p>
</body>
</html>
Output :
Click me away!
Click me too!
jQuery submit() :
jQuery submit event is sent to the element when the user attempts to submit a
form.
This event is only attached to the <form> element. Forms can be submitted either
by clicking on the submit button or by pressing the enter button on the keyboard
when that certain form elements have focus. When the submit event occurs, the
submit() method attaches a function with it to run.
Syntax:
$(selector).submit()
$(selector).submit(function)
Parameter Description
p{
margin: 0;
color: blue;
}
div,p {
margin-left: 10px;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Type 'javatpoint' to submit this form finally.</p>
<form action="javascript:alert( 'success!' );">
<div>
<input type="text">
<input type="submit">
</div>
</form>
<span></span>
<script>
$( "form" ).submit(function( event ) {
if ( $( "input:first" ).val() === "javatpoint" ) {
$( "span" ).text( "Submitted Successfully." ).show();
return;
}
$( "span" ).text( "Not valid!" ).show().fadeOut( 2000 );
event.preventDefault();
});
</script>
</body>
</html>
Output :
Submit
The css() method sets or returns one or more style properties for the selected
elements.
To return the value of a specified CSS property, use the following syntax:
css("propertyname");
css("propertyname","value");
example program
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css("background-color", "yellow");
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
</body>
</html>
css({"propertyname":"value","propertyname":"value",...});
example program
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
</body>
</html>
Example
$("p").append("Some appended text.");
Example
$("p").prepend("Some prepended text.");
The jQuery remove() method also accepts one parameter, which allows you to filter
the elements to be removed.
Example :
$("p").remove(".test");
This example removes all <p> elements with class="test" and class="demo":
Example :
$("p").remove(".test, .demo");
JQuery is a great tool which provides a rich set of AJAX methods to develop
next generation web applications.
With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a
remote server using both HTTP Get and HTTP Post - And you can load the external
data directly into the selected HTML elements of your web page!
The load() method loads data from a server and puts the returned data into the
selected element.
Syntax:
$(selector).load(URL,data,callback);
The required URL parameter specifies the URL you wish to load.
The optional data parameter specifies a set of querystring key/value pairs to send
along with the request.
The optional callback parameter is the name of a function to be executed after the
load() method is completed.
The following example loads the content of the element with id="p1", inside the file
"demo_test.txt", into a specific <div> element:
Example :
$("#div1").load("demo_test.txt #p1");
The optional callback parameter specifies a callback function to run when the load()
method is completed. The callback function can have different parameters:
The following example displays an alert box after the load() method completes. If
the load() method has succeeded, it displays "External content loaded successfully!",
and if it fails it displays an error message:
Example
$("button").click(function(){
if(statusTxt == "error")
});
});
GET is basically used for just getting (retrieving) some data from the server. Note:
The GET method may return cached data.
POST can also be used to get some data from the server. However, the POST method
NEVER caches data, and is often used to send data along with the request.
To learn more about GET and POST, and the differences between the two methods,
please read our HTTP Methods GET vs POST chapter.
Syntax:
$.get(URL,callback);
The required URL parameter specifies the URL you wish to request.
The following example uses the $.get() method to retrieve data from a file on the
server:
Example
$("button").click(function(){
});
});
The second parameter is a callback function. The first callback parameter holds the
content of the page requested, and the second callback parameter holds the status
of the request.
<%
%>
Syntax:
$.post(URL,data,callback);
The required URL parameter specifies the URL you wish to request.
The optional data parameter specifies some data to send along with the request.
The following example uses the $.post() method to send some data along with the
request:
Example
$("button").click(function(){
$.post("demo_test_post.asp",
city: "Duckburg"
},
function(data, status){
});
});
Then we pass in some data to send along with the request (name and city).
The ASP script in "demo_test_post.asp" reads the parameters, processes them, and
returns a result.
The third parameter is a callback function. The first callback parameter holds the
content of the page requested, and the second callback parameter holds the status
of the request.
<%
dim fname,city
fname=Request.Form("name")
city=Request.Form("city")
%>
● Hide
● Show
● Fade
● Slide
● Animate
Hide :
You can apply any jQuery selector to select any element and then apply jQuery
hide() method to hide it. Here is the speed predefined parameter
("slow","normal",or "fast") or user defined parameter (<milliseconds in numbers>)
of all the parameters which gives you a solid control over the hiding effect
Syntax:
$(selector).hide( [speed, callback] );
Sample code:
$("button").click(function(){
$("p").hide(1000);
});
Show:
You can apply any jQuery selector to select any element and then apply jQuery
show() method to show it. Here is the speed predefined parameter
("slow","normal",or "fast") or user defined parameter (<milliseconds in numbers>)
of all the parameters which gives you a solid control over the hiding effect
Syntax:
Sample code:
$("button").click(function(){
$("p").show(1000);
});
Fade:
jQuery gives us two methods - fadeIn() and fadeOut() to fade the elements in and
out of visibility.The jQuery fadeIn() method is used to fade in a hidden element
whereas fadeOut() method is used to fade out a visible element.The parameters as
same as previous effects.
Syntax:
Sample code:
$(document).ready(function() {
$("#show").click(function(){
$("#box").fadeIn(1000);
});
$("#hide").click(function(){
$("#box").fadeOut(1000);
});
});
//fade toggle
$("#button").click(function(){
$("#box").fadeToggle(1000);
});
Slide:
jQuery gives us two methods - slideUp() and slideDown() to slide up and slide
down the elements respectively. The jQuery slideUp() method is used to slide up
an element whereas slideDown() method is used to slide down.
Syntax:
Sample code:
//slide down
$("#flip").click(function(){
$("#panel").slideDown();
});
// slide up
$("#flip").click(function(){
$("#panel").slideUp();
});
//slide toggle
$("#button").click(function(){
$("#box").slideToggle(1000);
});
Animate:
Syntax:
Sample code:
$("button").click(function(){
$("div").animate({left: '250px'});
});