JQuery Tutorial #4: Rules of Writing jQuery Code
After learning the jQuery ready() event, this time we will take a brief look at the basic rules for using jQuery code and the meaning of jQuery Object and jQuery Event.
Definition of jQuery Object ($)
Throughout jQuery’s use, it’s almost always preceded by a $ sign. The dollar sign ‘$’ ( dollar sign ) is a shortcut to the jQuery Object . In this jQuery Object , all jQuery functions are located. For example, to find an HTML element that has the id = “button” attribute , we could write:
$("#button")
If for some reason we cannot use the $ sign (usually because it collides with another library), we can use jQuery , as follows:
jQuery("#button");
Definition of jQuery Action / jQuery Event
To be able to do ‘something’ with HTML elements, we just need to connect jQuery Object writing with jQuery Action , also known as jQuery Event. The basic format is as follows:
$(selector).action();
Selector is used to find which elements of HTML to manipulate. It can be a paragraph <p>, an <img> image, or something more complex, such as the first <tr> element of the second table. We will cover the types of jQuery selectors in the next tutorial.
Action is something that we can do with the HTML element, whether to hide it, display it, change the color, add a new element, etc. Actions are similar to Events in JavaScript, but with the addition of a variety of other features. In jQuery, an action can be linked to another action, otherwise known as chaining.
Here’s an example of writing a jQuery Object , selectors and actions :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JQuery Tutorial | Techbriefers</title>
<script src="jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>JQuery Tutorial by Techbriefers</h1>
<button id="button_hide">To Hide</button>
<button id="button_show">To Show</button>
<button id="button_small">To Zoom Out</button>
<button id="button_red">To Color Red</button>
<script>
$(document).ready(function () {
$("#button_hide").click(function () {
$("h1").hide();
});
$("#button_show").click(function () {
$("h1").show();
});
$("#button_small").click(function () {
$("h1").css("font-size", "20px");
});
$("#button_red").click(function () {
$("h1").css("color", "red");
});
});
</script>
</body>
</html>
Please try it yourself from the codepen link below:
See the Pen Basic Rules of Writing jQuery Code by Techbriefers (@techbriefers) on CodePen.