jQuery is a fast, small, and feature-rich JavaScript library that simplifies various tasks in web development like HTML document traversal and manipulation, event handling, animation, and AJAX interaction. Understanding jQuery syntax and basic concepts is crucial for harnessing its power to enhance web development projects.

1. Including jQuery in HTML Document

To use jQuery in an HTML document, you can include it by downloading the jQuery library and linking it in the <head> section, by using a Content Delivery Network (CDN), or by embedding the jQuery code directly into the HTML document.

<!-- Downloaded jQuery library -->
<script src="jquery.min.js"></script>

<!-- Using jQuery from CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<!-- Embedding jQuery code directly -->
<script>
  // jQuery code goes here
</script>

2. Document Ready Function

The $(document).ready() function in jQuery is used to execute code when the DOM (Document Object Model) is fully loaded and ready for manipulation. It ensures that the code inside the function runs only after the DOM is fully loaded.

$(document).ready(function() {
  // jQuery code to execute after DOM is fully loaded
});

3. Selecting Elements

jQuery selectors allow you to select and manipulate HTML elements. You can select elements by their tag name, class, ID, attributes, and more.

// Selecting elements by tag name
$("p")

// Selecting elements by class
$(".example")

// Selecting elements by ID
$("#header")

// Selecting elements by attribute
$("input[type='text']")

4. DOM Manipulation

jQuery simplifies DOM manipulation by providing methods to add, remove, or modify HTML elements and their attributes.

// Adding content to an element
$("#container").html("<p>Hello, jQuery!</p>");

// Appending content to an element
$("#list").append("<li>Item 1</li>");

// Removing an element
$("#btn").remove();

// Modifying CSS properties
$("#box").css("background-color", "blue");

5. Event Handling

jQuery allows you to attach event handlers to HTML elements to respond to user actions like clicks, mouse movements, keypresses, etc.

// Click event handler
$("#btn").click(function() {
  alert("Button clicked!");
});

// Hover event handler
$("#image").hover(function() {
  $(this).css("opacity", "0.5");
}, function() {
  $(this).css("opacity", "1");
});

6. AJAX Interaction

jQuery simplifies AJAX (Asynchronous JavaScript and XML) requests, allowing you to fetch data from a server without refreshing the entire page.

// AJAX GET request
$.get("data.json", function(data) {
  $("#result").html(data);
});

// AJAX POST request
$.post("submit.php", $("#form").serialize(), function(response) {
  $("#message").html(response);
});

Example: jQuery Animation

$(document).ready(function() {
  // Animate the box
  $("#box").animate({
    left: '250px',
    opacity: '0.5',
    height: '150px',
    width: '150px'
  }, 'slow');
});



Practice Excercise Practice now