About Lesson
Basic Syntax:
The jQuery syntax always begins with the $ symbol:
$(selector).action();
- $: Represents jQuery.
- selector: Selects the HTML element(s).
- action: Specifies the action to perform.
Basic Example:
JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Basics</title>
<style>
.my-div {
width: 200px;
height: 100px;
background-color: lightblue;
text-align: center;
line-height: 100px;
margin: 20px auto;
border: 1px solid blue;
}
</style>
</head>
<body>
<h1 id="heading">Welcome to jQuery!</h1>
<p id="paragraph">This is a sample paragraph.</p>
<div class="my-div">Click Me</div>
<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<!-- Custom Script -->
<script>
// jQuery Practice Code
$(document).ready(function () {
// Select and change the text of an element
$("#heading").text("Hello, jQuery!");
// Change the HTML of an element
$("#paragraph").html("<strong>This paragraph text has been updated!</strong>");
// Modify CSS styles dynamically
$(".my-div").css({
"color": "white",
"background-color": "darkblue",
"border-radius": "10px",
});
// Event: Change background color on click
$(".my-div").click(function () {
$(this).css("background-color", "green").text("Clicked!");
});
});
</script>
</body>
</html>
Explanation of Code:
- $(document).ready(function() { … });
Ensures that the DOM is fully loaded before executing any jQuery code. - $(“#heading”).text(“Hello, jQuery!”);
Changes the text of the <h1> element with ID heading. - $(“#paragraph”).html(“<strong>This paragraph text has been updated!</strong>”);
Updates the HTML content of the paragraph. - $(“.my-div”).css({…});
Dynamically modifies the CSS styles of the <div> with class my-div. - Event Handling:
- The .click() method attaches a click event to div.my-div.
- Changes the background color and text when clicked