What is jQuery?

jQuery is a lightweight JavaScript library designed to simplify coding by allowing you to write less while accomplishing more. It makes working with JavaScript on your website easier by condensing complex tasks that typically require multiple lines of code into simple, callable methods.

Additionally, jQuery streamlines many advanced JavaScript functions, such as AJAX calls and DOM manipulation, making them more accessible and efficient.

The implications of jQuery

jQuery includes the following.

HTML/DOM manipulation CSS manipulation HTML event methods Effects and animations AJAX (Asynchronous Javascript and XML) Utilities

Jquery also has plugins for almoost any task.

jQuery syntax and how to use it

With jQuery you slect (query) HTML elements and perform “actions” on them.

Basic syntax is $(selector).action()

A $ symbol to define/access jQuery A (selector) to “query (or find)” HTML elements A jQuery action() to be performed on the element(s)

Examples: $(this).hide() - hides the current element

$(“p”).hide() - hides all <p> elements

$(“.test”).hide() - hides all elements with class=”test”

$(“#test”).hide() - hides the element with id=”test”

Popcorn hack

Write in one of the comments where the selector is.

$(document).ready(function(){     // 
    $("button").click(function(){ //
      $("p").hide();              //
    });                           //
  });                             //

The element Selector

$(“p”) The #id Selector $(“#test”) The .class Selector $(“.class”) The Document Ready Event

All jQuery methods begin inside a document ready event:

$(document).ready(function(){

    // jQuery methods go here...
  
  });

This is to prevent any jQuery code from running before the document is finished loading (is ready).

It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.

Reason:

Trying to hide an element that is not created yet Trying to get the size of an image that is not loaded yet

$(function(){
    
    // An even quicker way to do it
    // jQuery methods go here...
  
  });

jQuery methods and event handling What are Events?

All the different visitors’ actions that a web page can respond to are called events Mouse Events Keyboard Events Form Events Document/Window Events click keypress submit load dblclick keydown change resize mouseenter keyup focus scroll mouseleave blur unload

Making requests with AJAX

AJAX, which stands for Asynchronous JavaScript and XML, enables web pages to update asynchronously more efficiently. It operates on a promise-based system, where a JavaScript Promise represents the eventual success or failure of an asynchronous request.

WHy use jQuery AJAX over a normal aync request or AJAX request?

Against a normal sun request AJAX jas a lot of advantages: Easier Error Handling: Promises are much easier to deal with than callbacks. If an error occurs in a promise, it will be passed down to the next catch() clause. Simpler API Chaining: If you want to wait for one operation to finish before starting another one you can simply use .then().

Normal async request:

getUserLocation(function(error, location) {
    if (error) {
        console.error('Error:', error);
    } else {
        getForecast(location, function(error, forecast) {
            if (error) {
                console.error('Error:', error);
            } else {
                console.log('Forecast:', forecast);
            }
        });
    }
});

Ajax requests wihtout any library

fetch('api/location')
.then(response => response.json())
.then(location => fetch('api/forecast/' + location))
.then(response => response.json())
.then(forecast => {
    console.log('Forecast:', forecast);
})
.catch(error => {
    console.error('Error:', error);
});

Ajax requests with jQuery

$.ajax({ url: 'api/location', method: 'GET', dataType: 'json' })
.then(function(location) {
    return $.ajax({ url: 'api/forecast/' + location, method: 'GET', dataType: 'json' });
})
.then(function(forecast) {
    console.log('Forecast:', forecast);
})
.catch(function(error) {
    console.error('Error:', error);
});

Using AJAX is much easier to read compared to the callback system. However, when comparing jQuery AJAX with JavaScript’s native version, the differences are minimal. The choice ultimately depends on which syntax you prefer.

As noted earlier, jQuery AJAX is built on top of the older JavaScript implementation, allowing it to support older browser versions.

Jquery’s use with PBL

jQuery’s primary function is to make your site dynamic and responsive to user input. For our projects, the key aspect of this is retrieving data from the backend and generating HTML from it.

%%html
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        .post {
            border: 1px solid #ddd;
            margin-bottom: 20px;
            padding: 20px;
            border-radius: 5px;
        }
        .like-count {
            color: #007BFF;
        }
    </style>
</head>
<body>

<div id="posts"></div>

<script>
// Fake API function
function getAPI() {
    return [
        {id: 1, content: 'Dogs are man\'s best friend.', likes: 10},
        {id: 2, content: 'Dogs have an exceptional sense of smell.', likes: 20},
        {id: 3, content: 'There are hundreds of different dog breeds.', likes: 30}
    ];
}

$(document).ready(function(){
    var posts = getAPI();
    $.each(posts, function(i, post) {
        var postHtml = '<div class="post"><h2>Post ' + post.id + '</h2><p>' + post.content + '</p><p class="like-count">' + post.likes + ' likes</p></div>';
        $('#posts').append(postHtml);
    });
});
</script>

</body>

Animations with JQuery

You can also create animations in JQuery.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  // Reset CSS properties to their original values
  $("div").css({
    left: '0px',
    opacity: '1',
    height: '100px',
    width: '100%'
  });

  $("button").click(function(){
    $("div").animate({
      left: '250px',
      opacity: '0.5',
      height: '150px',
      width: '100%'
    });
  });
});
</script>
</head>
<body>

<button>Start</button>

<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

</body>
</html>

CRUD Principles:

What Does CRUD Stand For?

Create, Read, Update Delete What Does CRUD Do?

These four basic operations represent the fundamental actions that can be performed on data in a computer system or a database. How Can CRUD Be Applied to jQuery and Beyond?

jQuery: jQuery is a JavaScript library that simplifies HTML document traversal and manipulation. You can use jQuery to perform CRUD operations on the client side, interacting with the DOM. Here’s a brief overview:

Create (C)

// Create a new element and append it to a table
$('#myTable').append('<tr><td>New Data</td></tr>');

Read (R)

// Read data from a table
$('#myTable tr').each(function() {
    console.log($(this).text());
  });  

Update (U)

// Update data in a table
$('#myTable td:contains("Old Data")').text('Updated Data');

Delete (D)

// Delete a row from a table
$('#myTable td:contains("Data to Delete")').closest('tr').remove();

Beyond Jquery:

In more advanced web development, CRUD operations are typically handled using server-side technologies and databases. Frameworks like Node.js, Express, Django, and Flask are commonly used for backend development, while databases such as MySQL, MongoDB, and PostgreSQL store and manage the data.

Demonstration fo Applying CRUD to TABLES:

Assuming a simple HTML table with the ID “mytable”;

<table id="myTable">
  <tr>
    <th>Data</th>
  </tr>
  <tr>
    <td>Row 1</td>
  </tr>
  <tr>
    <td>Row 2</td>
  </tr>
</table>

Create (C)

// Create a new row and append it to the table
$('#myTable').append('<tr><td>New Row</td></tr>');

Read (R)

// Read and log data from the table
$('#myTable tr').each(function() {
    console.log($(this).text());
});

Update (U)

// Update data in the first row of the table
$('#myTable tr:first-child td').text('Updated Row');

Delete (D)

// Delete the second row from the table
$('#myTable tr:nth-child(2)').remove();