Advantages of jQuery and Syntax
Introduction
jQuery is a fast, small, and feature-rich JavaScript library that simplifies client-side scripting of HTML. Its motto is "Write Less, Do More."
Advantages of jQuery
$("p.intro") selects all paragraphs with class intro.hide(), show(), fadeIn(), etc., without complex coding.jQuery Syntax
The basic jQuery syntax is:
$(selector).action();
Example
$(document).ready(function(){
$("p").hide();
});
<p> elements. The $(document).ready() method ensures code runs only after the page loads.
jQuery Selectors
Definition
jQuery selectors are used to select and manipulate HTML elements. They work similarly to CSS selectors and allow easy access to elements in the DOM.
The selector syntax always starts with the dollar sign:
$(selector)
Types of jQuery Selectors
Selects elements based on the HTML tag name.
Syntax$("element-name")
Example
$("p")
Selects a single element using its unique id.
$("#id")
Example
$("#header")
Selects all elements having a specific class name.
Syntax$(".class-name")
Example
$(".intro")
Example Program
<p class="intro">Hello</p>
<p id="msg">Welcome</p>
<script>
$(document).ready(function(){
$(".intro").hide(); // class selector
$("#msg").show(); // id selector
$("p").css("color","red"); // element selector
});
</script>
jQuery Events and Effects
Definition
jQuery events are actions that occur when a user interacts with a web page, such as clicking, typing, or submitting a form. jQuery makes event handling easy and cross-browser compatible.
Common jQuery Events
Example
$("#loginBtn").click(function(){
alert("Login button clicked");
});
This runs the function when the button with id loginBtn is clicked.
Document Ready Event
$(document).ready(function(){
// jQuery code here
});
It ensures the code runs only after the page is fully loaded.
Definition
jQuery effects are used to add visual animations and dynamic behavior to web pages with minimal code. jQuery effects include showing, hiding, fading, sliding, and custom animations.
Common jQuery Effects
Example
$("#box").fadeIn(1000);
This fades in the element with id box over 1 second (1000 milliseconds).
jQuery Manipulation Methods
Definition
jQuery manipulation methods are used to modify the content, attributes, CSS, and structure of HTML elements dynamically. They make DOM manipulation simple and efficient.
Types of jQuery Manipulation Methods
These methods change the text or HTML inside elements.
$("#msg").text("Hello");
Changes the text content of the element with id msg.
Used to get or change element attributes.
$("#img").attr("src", "pic.jpg");
Changes the src attribute of the image element.
Used to modify styles and classes of elements dynamically.
$("p").css("color", "red");
Changes the text color of all <p> elements to red.
Used to add or remove HTML elements from the page.
$("#list").append("<li>New Item</li>");
Adds a new list item at the end of the element with id list.