jQuery
Contents
jQuery¶
jQuery is a JavaScript library which makes it much easier to access and modify elements of your page with JavaScript.
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:
through local files
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 at the end of the <body>
:
<body>
<!-- content of your page -->
<script src="js/jquery-3.6.0.min.js"></script>
</body>
It’s possible to load JavaScript in the <head>
, but this will slow down the loading of the page. So only if necessary, JavaScript should be loaded into the head. (If it modifies the DOM.)
<head>
<script src="js/file_name.js"></script>
</head>
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
<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. (You could write jQuery
instead of the $
. The selector addresses the element(s) we want to change with our code. These selectors follow the CSS selectors syntax.
// select by id
$('#some-id')
// select by class
$('.some-class')
// select by tag
$('tag')
Comparison between JavaScript and jQuery:
// 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. { :, :}
. (The latter is a key:value
pair.)
One possible solution:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>(Java)Scripted Story</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div id="div-1" class="prevent-select" onclick="random_color('#div-1');">1</div>
<div id="div-2" class="prevent-select" onclick="random_color('#div-2');">2</div>
<div id="div-3" class="prevent-select" onclick="random_color('#div-3');">3</div>
<div id="div-4" class="prevent-select" onclick="random_color('#div-4');">4</div>
<!-- Import JavaScript files -->
<script type="text/javascript" src="js/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
js/main.js
// Assign a random background color to the element that was clicked
function random_color(id) {
// Get 3 random color values
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
// Combine them as a string with string formatting
var color = `rgb(${r}, ${g}, ${b})`;
// Get random values for the position of the button
var top = Math.floor(Math.random() * 80).toString() + 'vh';
var left = Math.floor(Math.random() * 80).toString() + 'vw';
// Change the color of the element according to the passed id
$(id).css({
'background-color': color,
'top': top,
'left': left
});
}
Event handling¶
From now on we will use an external js
file for our own JavaScript code:
<body>
<!-- content of your page -->
<script src="js/jquery-3.6.0.min.js"></script>
<script src="js/main.js"></script>
</body>
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() {
$(selector).click(function() {
// code to be executed on click
})
})
The first part
$(document).ready(function() {
// all code in here
})
means that the code inside the {}
will be executed when the DOM (Document Object Model) of your page (all the elements) is loaded.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>(Java)Scripted Story</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div id="div-1" class="button prevent-select">1</div>
<div id="div-2" class="button prevent-select">2</div>
<div id="div-3" class="button prevent-select">3</div>
<div id="div-4" class="button prevent-select">4</div>
<!-- Import JavaScript files -->
<script type="text/javascript" src="js/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
(The buttons have a new class button
, therefore the onclick
attribute was removed.)
js/main.js
$(document).ready(function() {
$('.button').click(function() {
// Get the id of the clicked element
// (this) refers to the object itself
var id = $(this).attr('id');
// Preceed it with a #
id = '#' + id;
// Call the function and insert the id
random_color(id);
})
})
// Assign a random background color to the element that was clicked
function random_color(id) {
// Get 3 random color values
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
// Combine them as a string with string formatting
var color = `rgb(${r}, ${g}, ${b})`;
// Get random values for the position of the button
var top = Math.floor(Math.random() * 80).toString() + 'vh';
var left = Math.floor(Math.random() * 80).toString() + 'vw';
// Change the color of the element according to the passed id
$(id).css({
'background-color': color,
'top': top,
'left': left
});
}
One possible solution:
js/main.js
$(document).ready(function() {
$('.button').click(function() {
// Get the id of the clicked element
// (this) refers to the object itself
var id = $(this).attr('id');
// Preceed it with a #
id = '#' + id;
// Call the function and insert the id
random_color(id);
random_size(id);
})
})
// Assign a random background color to the element that was clicked
function random_color(id) {
// Get 3 random color values
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
// Combine them as a string with string formatting
var color = `rgb(${r}, ${g}, ${b})`;
// Get random values for the position of the button
var top = Math.floor(Math.random() * 80).toString() + 'vh';
var left = Math.floor(Math.random() * 80).toString() + 'vw';
// Change the color of the element according to the passed id
$(id).css({
'background-color': color,
'top': top,
'left': left
});
}
// Assign random width and height
function random_size(id) {
// Return random sizes:
var w = Math.floor(Math.random() * 100 + 1);
// The + 1 assures that the width can't be 0.
// The same in one line:
var h = Math.floor(Math.random() * 100 + 1);
// Change css properties:
$(id).css({
'width':`${w}vw`,
'height': `${h}vh`
});
}
Example: Animation with arrays¶
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>(Java)Scripted Story</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="animated-headlines">
<div id='line_1'>uncreative</div>
<div id="line_2">writing</div>
</div>
<!-- Import JavaScript files -->
<script type="text/javascript" src="js/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
css/style.css
* {
box-sizing: border-box;
}
body {
font-family: monospace;
width: 100vw;
height: 100vh;
background-color: lightgoldenrodyellow;
}
.animated-headlines {
font-size: 10rem;
color: maroon;
position: fixed;
top: 10vw;
left: 10vw;
}
js/main.js
var i = 0; // Counter to decide which text will be changed.
var interval = 1500; // Pause between title changes in milliseconds.
$(document).ready(function() {
setInterval(random_word, interval);
});
function random_word() {
// Array with words
var line_1 = ['uncreative', 'interactive', 'unusual', 'boring', 'disruptive', 'experimental'];
var line_2 = ['writing', 'design', 'identities', 'concepts', 'ideas', 'actions', 'poetry', 'work'];
// Check if the variable i is even, then change line_1
if (i % 2 == 0) {
var random_text_1 = line_1[Math.floor(Math.random() * line_1.length)];
$('#line_1').text(random_text_1);
}
// Otherwise (i is odd) change line_2
else {
var random_text_2 = line_2[Math.floor(Math.random() * line_2.length)];
$('#line_2').text(random_text_2);
}
i++;
}