script
tag.
[html]
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
</head>
[/html]
Now, add some event functions in DOM, it is good to practice write all the functions inside of a $(document).ready() function. div
element "left".When hovered using mouse on left content area, the area color chanes from pink to red.div
element "center".When clicked on that area, an alert box appears showing some message.div
element "right".When clicked on that area, the element area will be hidden.script
tag. See the Following code to check document page, whether fully loaded or not. When the document page loading is finished then the executed code block look like this.
[javascript]
$(document).ready(function() {
// When DOM is ready stuff this part
});
[/javascript]
In below Example, use jQuery hover function demo with the help of jQuery library function to show how it will interact with programmer.
[html]
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery@*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link type="text/css" rel="stylesheet" href="style.css">
</head>
<body>
<div id="left">
<h2>Left Content Area</h2>
<p>This area will contain the left content area.
We will populate this area with images and text. </p>
</div>
<div id="center">
<h2>Center Content Area</h2>
<p>This area will contain the center content area.
This area will contain the main articles. </p>
</div>
<div id="right">
<h2>Right Content Area</h2>
<p>This area will contain the right content area.
We will populate this area with links and text.</p>
</div>
<script>
$(document).ready(function() {
$("#left").hover(function(){
$(this).css("background-color", "red");
}, function(){
$(this).css("background-color", "pink");
});
});
$(document).ready(function(){
$("#center").click(function() {
alert("The Paragraph was clicked");
});
});
$(document).ready(function(){
$("#right").on("click", function(){
$(this).hide();
});
});
</script>
</body>
</html>
[/html]
[html]
#left {
width: 300px;
float: left;
padding: 15px;
margin: 10px;
background: #f8f8f8;
border: solid 2px black;
}
#center {
width: 325px;
float: left;
padding: 15px;
margin: 10px;
border: solid 2px black;
}
#right {
width: 300px;
padding: 15px;
margin: 10px;
float: left;
background: #f0efef;
border: solid 2px black;
}
[/html]
Output:
external.js
file.
[javascript]
/* Save this Filename: external.js */
$(document).ready(function() {
$("p").click(function() {
alert("Paragraph was clicked");
});
});
[/javascript]
Then include external.js
file in main document as shown below.
[html]
<html>
<head>
<title>jQuery Examples</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"type="text/javascript"></script>
<script src="external.js"></script>
</head>
<body>
<h1>Welcome to SPLessons</h1>
<div>Click on this paragraph</div>
</body>
</html>
[/html]