Javascript
JQuery
☝️ As of January 1, 2017, 4Geeks has decided to stop teaching jQuery because we think it is no longer necessary for someone to become a front-end developer. However, we are leaving the lessons and replit’s here if you would like to learn it on your own.
Do more stuff with less code.
jQuery is a library (set of functions) available to JavaScript developers to make their lives easier (just like the Math object that we use for Math.random). jQuery is NOT another language. It is the same as JavaScript, and you don’t need to use it if you don’t want to.
When jQuery was the new thing (10 years ago), people loved it. It made cross-browser JS so much easier. It taught us a few new tricks and it made AJAX and animations dead simple (which was pretty tricky back when most of the world was on IE6!).
Then came The Smartphone Times. This spelled disaster for jQuery. Thanks to slower, inferior CPUs with less memory and often less bandwidth, smartphones just weren’t cut out for lugging around all the goodness that jQuery provided – especially if you were only using 10% of it.
Today, the browsers have agreed on some of the crap that jQuery The Negotiator had been helping them with all along. So they actively and rapidly trimmed the fat.
Do we still need jQuery? Maybe not. The usage of its library is clearly declining, but it still doubles any of its siblings (Angular, React, etc.), and Bootstrap still uses it a lot!
Query can do 5 things really well, and those 5 things brought jQuery to the point that it is being used on almost every website:
Since jQuery is a library, it needs to be installed as a JavaScript library. All JavaScript libraries need to be imported using the <script>
tag – like this:
1<script src="myscripts.js"></script>
First, you need the actual jQuery code. You have two options for that: (1) Download the jQuery source code (recommended) or (2) Import the code from a public server (CDN):
To download jQuery, go to code.jquery.com and pick the last MINIFIED version of jQuery available. Right-click on it and "save the file as…". Save that file in your project directory.
Then, use the <script>
tag to import that file into your website. Place the <script>
tag inside of the <head>
tag before any other JavaScript tag.
Content Distribution Networks are servers that are used specifically to store libraries and resources to be used by other websites. For example, libraries like Bootstrap and jQuery are normally available in several CDN’s.
We recommend the Google CDN: look for jQuery and copy the <script>
of the latest version of jQuery available. Paste that script tag before any other JavaScript script tag inside your website <head>
.
1<!DOCTYPE html> 2<html> 3 <head> 4 <title>repl.it</title> 5 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 6<!– any other JS scripts that use jQuery should be imported below jQuery –> 7 </head> 8<body> 9</body> 10</html>
jQuery is a part of JavaScript! jQuery syntax can be tricky at the beginning, but after a few days you will understand that it is the same JavaScript syntax but just being used in a different way.
All of jQuery’s functionalities are embedded into an object: The jQuery object. The idea is that everything is done with that one global symbol. This can be used with either a dollar sign $
or with "jQuery" (The dollar $ is just a shortcut for "jQuery"). You can use whichever you like:
1$(‘css_selector’) 2jQuery(‘selector’) 3console.log($ === jQuery); // "true"
To avoid feeling confused, you will need to understand that jQuery is ADDICTED to inline functions. For example, the code below is very common when using jQuery to listener for the click event. The handler function is declared in the same line – like this:
1$(element).click(function() { 2 //your function code here 3});
This code is exactly the same as this other one:
1var clickHandler = function() { 2} 3$(element).click(clickHandler);
In the example above, we are adding an event listener for when the user clicks on a DOM element.
You are used to working with function parameters like this:
1functionName(param1, param2, param3); 2 //function call with 3 parameters
When using jQuery, the best practice is to always pass one "settings object" as a parameter instead of passing several parameters separated by commas – like this:
1var settingsObj = { 2param_key1 : param_value1, 3param_key2 : param_value2, 4param_key3 : param_value3 5} 6functionName(settingsObj); 7 //Function call with 3 parameters inside the settingsObj
☝️ If you use jQuery, you need to be comfortable using parameters like the "Settings Object."
We have a section that talks just about events, but it is a good idea to talk about the "ready event" right now because it is one of the first lines of code written on almost every website that uses jQuery.
The flow of your website begins on the "ready" event. That event is called when the website and all of its elements have finished loading. As a developer, you will need to add an event listener for the ready event like this:
1$( document ).ready(function() { 2 // Handler for .ready() called. Your code here 3});
jQuery really helps when working with classes because the only way to update a class with vanilla JS is using the .className attribute of the DOM element (that is a string).
For example, if you want to remove one specific class from an element you will first have to get the value of the class attribute as a string. Next, create a new string – just like the first one – but without that particular class.
1var elm = document.getElementById(‘elementId’); 2var elmArray = document.getElementsByClassName(‘elementId’);
1var elem = $(‘#elementId’); 2var elemArray = $(‘.elm_class’);
1var myAnchor = document.createElement("A"); 2myAnchor.href="http://google.com"; 3myAnchor.target="_blank";
1var attributesObj = { 2href: ‘http://google.com’, 3parent: ‘_blank’ 4} 5$(‘<a>’,attributesObj); //the attributesObj is optional
1parent.appendChild(el);
1$(parent).append(el);
Vanilla JS doesn’t have a remove() function. You will have to call a removeChild function form the element’s parent.
1elm.parentNode.removeChild(elm);
1$( ".hello" ).remove(); //Remove all elements with class hello 2$( ".hello" ).empty(); //Remove all childs of elements with class hello 3var elements = $( ".hello" ).detach(); //Remove the elements from the DOM but return them to store them in a variable
1elm.parentNode.replaceChild(myNewHeading, elm); //being myNewHeding a DOM element
1$( "#div1" ).replaceWith( "<h1>This is a new heding</h1>" );
1var parent = document.querySelector(css_elector); 2var childs = parent.querySelectorAll(css_elector); 3childs.forEach(function(elm, index){ 4 5});
1$(css_selector).find(selector).each(function(index, elm){ 2 3});
1el.getAttribute(‘tabindex’); 2el.setAttribute(‘tabindex’, 3);
1$(el).attr(‘tabindex’); 2$(el).attr(‘tabindex’, 3);
☝️ These are the most used functions when working with the DOM. Please be advised that there are A LOT more functions available and that it is a good idea to eventually review all of them. Also, new functions are being created as JavaScript continues to evolve.
jQuery really helps when working with classes because the only way to update a class with vanilla JS is by using the .className attribute of the DOM element (which is a string).
For example, if you want to remove one specific class from an element, you will have to get the value of the class attribute as a string and then create a new string – just like the first one – but without that particular class.
1el.className += ‘ ‘ + className; //add 2el.className = el.className.replace("classname", ""); //remove
1$(el).addClass(className); 2$(el).removeClass(className);
1el.style.borderWidth = ’20px’; 2getComputedStyle(el)[ruleName];
1$(el).css(‘border-width’, ’20px’); 2$(el).css(ruleName);
1var classes = el.className.split(‘ ‘); 2 var existingIndex = classes.indexOf(className); 3 4 if (existingIndex >= 0) 5 classes.splice(existingIndex, 1); 6 else 7 classes.push(className); 8 9 el.className = classes.join(‘ ‘);
1$(el).toggleClass(className);
☝️ This are the most used functions to work with styles, there are a lot more functions and is a good idea to eventually review the rest of them.
You already know a lot about events because we went through the Javascript Events lesson earlier during this course.
jQuery does not add much value when working with events, we have the same concepts: Event-Names, Listeners and Handlers. jQuery can listen to the exact same events (click, hover, etc.) and you have the same event information passed as a parameter in the handler function.
The only really great advantage when working with jQuery events is the jQuery selector, because now you can attach a listener to several objects at the same time without having to iterate through all of them. For example, lets try to add a listener to the click event on all the elements with the class ".btn"
1var myElementsArray = document.querySelectorAll(‘.btn’); 2myElementsArray.forEach(function(elm,index){ 3elm.addEventListener("click",function(){ 4alert(‘s’); 5}); 6});
1$(‘.btn’).on( "click", function(){ 2 //your code here 3});
🔗 To continue reading about events we recommend this reading.
jQuery really helps when working with classes because the only way to update a class with vanilla JS is using the .className attribute of the DOM element (that is a string).
For example, if you want to remove one specific class from an element you will have to get the value of the class attribute as a string and create a new string just like the first one but without that particular class.
☝️ AJAX is going to be covered deeply in another lesson, here we are only going to introduce the syntax of ajax function.
1var request = new XMLHttpRequest(); 2request.open(‘GET’, ‘/my/url’, true); 3request.onload = function() { 4if (request.status >= 200 && request.status < 400) { 5 // Success! 6var data = JSON.parse(request.responseText); 7} else { 8 // We reached our target server, but it returned an error 9} 10}; 11request.onerror = function() { 12 // There was a connection error of some sort 13}; 14request.send();
1$.ajax({ 2 type: ‘GET’, 3 url: ‘/my/url’, 4 success: function(resp) { 5 6 }, 7 error: function() { 8 9 } 10});
1var http = new XMLHttpRequest(); 2var url = "/my/url"; 3var params = "lorem=ipsum&name=binny"; 4http.open("POST", url, true); 5//Send the proper header information along with the request 6http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 7http.onreadystatechange = function() { //Call a function when the state changes. 8if(http.readyState == 4 && http.status == 200) { 9alert(http.responseText); 10} 11} 12http.send(params);
1$.ajax({ 2 type: ‘POST’, 3 url: ‘/my/url’, 4data: {var1: value1, var2: value2 } 5 success: function(resp) { 6 7 }, 8 error: function() { 9 10 } 11});