jQuery

jQuery is a JavaScript library which makes it much easier to modify content of your page with JavaScript. It’s very easy to access HTML elements and change them.

Setup

In order to use the library we have to insert its code into our HTML file.

In general there are two options for including external libraries:

  1. through local files

  2. through a content delivery network (CDN)

Local

Download the latest compressed version and store it in a subfolder js inside your main folder. Insert it into the head

<head>
    <script src="js/jquery-3.6.0.min.js"></script>
</head>

or at the end of the <body>:

<body>
    <!-- content of your page -->
    <script src="js/jquery-3.6.0.min.js"></script>
</body>

CDN

CDN (Content Delivery Network) links are available through code.jquery.com.

Choose a suitable version, copy the link and insert it to your page like

<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

or at the end of the <body>:

<body>
    <!-- content of your page -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</body>

Syntax

jQuery code is written like JavaScript code and likely combined with vanilla JavaScript.

Basic syntax:

$(selector).action_to_perform()

The $ is used to specify that the following code is written in jQuery. The selector addresses the element(s) we want to change with our code. These selectors follow the CSS selectors syntax.

Example:

// change a css property with JavaScript
document.getElementById('object').style.height = h;

// the same written in jQuery
$('#object').css('height', h);

Even better, it’s possible to change multiple properties in one line:

// Javascript:    
document.getElementById("object").style.top = y;
document.getElementById("object").style.left = x;

// jQuery:
$('#object').css({'top':y, 'left':x});

(Take care with the notation of single and multiple properties: , vs. { :, :}.)

Task: Adapt the JavaScript code of the changing_color() function to jQuery.

One possible solution.

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        #object {
            width: 40vw;
            height: 40vw;
            background-color: rgb(235, 132, 66);
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
        #object:hover {
            cursor: pointer;
        }
    </style>
</head>
<body>

    <div id="object" onclick="change_color();"></div>

    <script src="js/jquery-3.6.0.min.js"></script>

    <script>
        function change_color() {
            // Return random colors.
            var r = Math.floor(Math.random() * 255);
            var g = Math.floor(Math.random() * 255);
            var b = Math.floor(Math.random() * 255);
            var a = Math.random();
            // Create a string with the variables r, g and b.
            var color = `rgba(${r}, ${g}, ${b}, ${a})`;
            // Change the background color.
            $('#object').css('background-color', color);
        }
    </script>

</body>
</html>

Event handling

From now on we will use an external js file for the custom JavaScript code:

<body>
    <!-- content of your page -->
    <script src="js/jquery-3.6.0.min.js"></script>
    <script src="js/main.js"></script>
</body>

It’s common to use a Document Ready Event before executing further jQuery code. This event will be fired when the DOM (Document Object Model) of your page is loaded.

main.js

$(document).ready(function() {
	// all code in here
})

Instead of calling a function directly through HTML as we did in the JavaScript chapter, we can add event listener to jQuery/ JavaScript code. For example to detect the click on an element we can write:

$(document).ready(function() {
    $('#object').click(function() {
        // code to be executed on click
    })    
})

(Remove onclick:change_color(); from index.html.)

main.js with the change_color() function:

$(document).ready(function() {
    $('#object').click(function() {
        change_color();
    })
})

function change_color() {
    // Return random colors.
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    var a = Math.random();
    // Create a string with the variables r, g, b, a.
    var color = `rgba(${r}, ${g}, ${b}, ${a})`;
    console.log(color);
    // Change the background color.
    $('#object').css('background-color', color);
}
Task: Write a new function that changes width and height of the object. Call it when the object is clicked.

More event methods

Example: Animation with arrays

Inspiration:

animation

Source.

animation2

index.html

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="css/style.css">
</head>
<body>

    <div class="animated-headlines">
        <span id='line_1'>uncreative</span>
        <br>
        <span id="line_2">code</span>
    </div>

    <div id="object"></div>

    <script src="js/jquery-3.6.0.min.js"></script>
    <script src="js/main.js" charset="utf-8"></script>

</body>
</html>

style.css

body {
    width: 100vw;
    height: 100vh;
    font-family: sans-serif;
}

.animated-headlines {
    font-size: 6rem;
    position: absolute;
    padding-top: 10vw;
    padding-left: 10vw;
    z-index: 1;
}

#object {
    width: 40vw;
    height: 40vh;
    background-color: rgb(235, 132, 66);
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

main.js

$(document).ready(function() {
    setTimeout(function() {
        new_title(0);
    }, 1500);
})

function new_title(i) {
    i++;
    if (i % 2 == 0) {
        var titles = ['uncreative', 'disruptive', 'dynamic', 'experimental'];
        var choice = titles[Math.floor(Math.random() * titles.length)];
        jQuery("#line_1").text(choice);
    }
    else {
        var titles = ['writing', 'language', 'code', 'poetry'];
        var choice = titles[Math.floor(Math.random() * titles.length)];
        jQuery("#line_2").text(choice);
    }
    var pause = Math.floor((Math.random() * 4) + 1) * 1000;
    setTimeout(function() {
        new_title(i);
    }, pause);
}