jQuery is a JavaScript library. It provides us with simple methods for achieving complex tasks. jQuery’s syntax allows us to side-step some of the intricacies of vanilla JavaScript.
<aside> <img src="/icons/list_purple.svg" alt="/icons/list_purple.svg" width="40px" />
By the end of this worksheet, you should be able to:
$(document).ready() function..hide(), .fadeOut(), .slideUp()) to manipulate elements dynamically..click() and .mouseenter() to trigger visual or behavioural changes..animate() and understand how to use camelCase for hyphenated CSS properties..css() and understand the difference between animating and directly styling elements.
</aside>jQuery is an external JavaScript library. In order to use jQuery in your HTML document you need to include the library in the page. This is done using the <script> tag in the <head> section of the page.
You can include jQuery from numerous online sources but this means you have to be connected to the Internet in order to use the library. We advise downloading the library into the same folder as your HTML documents. At the time of writing, the current version of jQuery is v3.7.1, which can be downloaded from https://jquery.com/download/. There may be a new version out by the time you read this.
There are several types available; you will likely want the compressed, production jQuery. Once you have downloaded jQuery, you can include it in your HTML document:
<script src="jquery-3.7.1.min.js"></script>
Once jQuery is included in an HTML page it allows you to manipulate the CSS properties of selectors (HTML tags, classes and IDs) via various events such as when the page loads or when an item is clicked. jQuery also comes packaged with some simple functions such as fades and slides — as well as the more complex .animate() function — which allows the animation of any CSS property that accepts a numerical value, e.g. font-size, top, width, border-width.
jQuery also provides a host of other useful tools for navigating and manipulating HTML documents. More on this next week.
jQuery code will be typed in the <head> section of the HTML document. You will require an additional set of <script> tags to the ones used to include the jQuery library.
Inside the <script> </script> we always call the “document ready function”. Given that we are placing our jQuery code in the head of our document, this function ensures that the page is fully loaded before any code we write can be run.
<script>
$(document).ready(function() {
// our code goes here
});
</script>
jQuery works by targeting selectors and then performing some action on them. (If ‘selectors’ sounds like a foreign concept, go back to the previous worksheet and ensure that you do before continuing.)
jQuery has its own syntax and it’s different to HTML and CSS. jQuery identifies selectors like this:
$('selector');