jQuery Basics - Engineering Level Notes
1. Exploring Fundamentals of jQuery
- jQuery is a fast, small, and feature-rich JavaScript library.
- Simplifies HTML document traversal and manipulation, event handling, animation, and Ajax.
- Syntax: $(selector).action()
- Example: $("p").click(function(){ alert("Hello!"); });
Advantages of jQuery:
- Easy to use and learn.
- Simplifies JavaScript programming.
- Cross-browser compatibility.
2. Loading and Using jQuery
Ways to load jQuery:
- Local: <script src="jquery-3.6.0.min.js"></script>
- CDN: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Usage Example:
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
3. Callback Functions
- Callback function is executed after current effect is finished.
- Example:
$("#btn").click(function(){
$("p").hide("slow", function(){
alert("Paragraph is now hidden.");
});
});
4. jQuery Selectors
Selectors are used to "find" or "select" HTML elements.
Examples:
- $("*") - Selects all elements
- $("p") - Selects all <p> elements
- $(".class") - Selects all elements with class="class"
- $("#id") - Selects the element with id="id"
Advanced Selectors:
- $("p:first") - Selects first <p> element
- $("ul li:first-child") - Selects first <li> in every <ul>
5. jQuery Methods and Manipulators
Common Methods:
- .hide(), .show(), .toggle()
- .fadeIn(), .fadeOut(), .fadeToggle(), .slideDown(), .slideUp()
DOM Manipulation:
- .html(), .text(), .attr(), .val()
Example:
$("button").click(function(){
$("#demo").text("Hello jQuery!");
});
6. jQuery Events
Common Event Methods:
- .click(), .dblclick(), .mouseenter(), .mouseleave()
- .mousedown(), .mouseup(), .hover()
Example:
$("p").click(function(){
$(this).hide();
});
7. jQuery Effects
Visual Effects:
- Hiding/Showing: .hide(), .show(), .toggle()
- Fading: .fadeIn(), .fadeOut(), .fadeToggle()
- Sliding: .slideDown(), .slideUp(), .slideToggle()
- Animation: .animate()
Example:
$("#btn").click(function(){
$("#box").fadeOut(1000);
});
8. jQuery and AJAX
What is AJAX?
- Asynchronous JavaScript and XML.
- Updates web pages asynchronously.
Using jQuery AJAX methods:
- .load(), .get(), .post(), .ajax()
Example using .load():
$("#btn").click(function(){
$("#div1").load("demo_test.txt");
});
Example using .ajax():
$.ajax({
url: "demo_test.txt",
success: function(result){
$("#div1").html(result);
});