JQuery and Javascript Javascript - a programming language to perform calculations/ manipulate HTML and CSS/ make a web page interactive JQuery - a javascript framework to help manipulate HTML and CSS JQuery Plugin - a script written by someone that relies on JQuery and solves interaction or layout needs. Require loading JQuery before loading the plugin script. API - application programming interface- read as documentation Link to JQuery API https://api.jquery.com/ Adding JQuery to Your Page First, you use one of these two methods to connect JQuery to your page. It is suggested that you put all javascript at the bottom of the page, right before the </body> tag. 1. Download at jquery.com, put in a js folder and link with a script tag: <script src="/js/jquery.min.js"></script> What goes in src is the path and name of file. May be different than what is here. 2. Load from a CDN <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.j s"></script> Next, you need a spot to write your javascript. You can write a separate.js file and link in the above section's step 1. We will write our javascript on the page by putting it between <script> tags. <script> // all of your javascript is written here </script> As far as the document is concerned, anything written between those tags is javascript (the same way anything written between <style> tags is CSS.
Javascript Comments Some of you may want to add comments as you write your javascript. There are two methods: // Single line comments get started with two forward slashes /* Multi line comments get wrapped in star slashes Just like in CSS */ First, You Have to Wait for Your Page to Be Ready First thing in your javascript file or in your <script> tags, you need to make JQuery wait for the page to be ready before calling all the rest of your javascript you write. There are multiple ways. Only use one. $(document).ready(function(){ // write your javascript here $(function(){ // write your javascript here Basic JQuery Pattern to Manipulate HTML Select an HTML element(s), then perform some action with it or its information $("some html via css selectors").dosomething(extra input); $("some html via css selectors") - selects one or more HTML element (whatever matches the CSS selector pattern you put in quotes)..dosomething() - a method (a pre-written function that gets performed on each of the HTML elements selected). Note the camel casing and that you will have to use the EXACT casing in the Query API What's a function? A function is a set of instructions that take an input, perform some type of action, and spits out an output. Although, sometimes you don't add any inputs. And sometimes you don't spit out any output (as in the case I write a function to make my page background blue. I can tell it
inside the function to make it blue without inputting anything or outputting anything. But that is not the reason for a function. Functions should ideally be re-usable for different cases (such as selecting any html and turning it any color). extra input - parameters (values and variable s you pass in to help with whatever the method is doing) What's a variable? A variable is just a holder for some value. Variables can be numbers, strings, booleans, arrays, objects, or functions (we'll talk about these later). Common Uses of JQuery to Manipulate HTML Set/Change the text within an HTML element.text("some text"); $(selector).text("hello, World"); Create an HTML element and Add it somewhere to the page.append("<tag></tag>"); Adds a new HTML element after your selector.appendto("<tag></tag>"); Adds a new HTML element inside your selector as the last element inside it.prepend("<tag></tag>"); Adds a new HTML element before your selector.prependto("<tag></tag>"); Adds a new HTML element inside your selector as the first element inside it $('h1').append('<h2></h2>'); What if we want to also add text. We Chain! Chaining - adding multiple methods to a selector $('h1').append('<h2></h2>').text("this is my h2!");
Add, Remove, Toggle a Class With this, you write CSS rules for different classes and use JQuery to add/remove the class to the HTML elements..addclass("some-class"); $(selector).addclass("my-class");.removeclass("some-class"); $(selector).removeclass("my-class");.toggleclass("some-class"); $(selector).toggleclass("my-class"); // this one adds the class if it isn't on the element and removes it if it is Change the CSS on an element Use this to directly apply CSS to an element (instead of writing css in <style> or in a separate sheet).css("some-property","some-value"); $('h1').css('color','red');.css( object of css values) $('h1').css({ 'color' : 'red', 'font-size' : '24px', 'padding-top' : '50px' What's an object? Think of an object as a definition list or a dictionary. It's a list of keys with values (which can be any variable type or value). Knowing how to use an object is very important to using JQuery plugins. We'll talk about these more later. Want to see more JQuery Methods for Manipulation? https://api.jquery.com/category/manipulation/
Events Javascript is all about interactivity. You mouse over something or click something and something happens. JQuery has a general method and specific methods to create interactivity. See https://www.w3schools.com/jquery/jquery_events.asp. General Method.on('event-name',function(){ // do something The event name can be: click, dblclick, mouseenter, mouseleave, mousedown, mouseup, submit, and a few more. Instead of the above with an event name and function, we can pass in an object of events..on({ mouseenter: function(){ // do something }, click: function(){ // do something } We probably won't use that method, but instead use specific methods: Event Specific Methods Note all these methods get an anonymous (unnamed) function as their parameter. In this function we write all the code we want to perform on that event. If we are changing a different element, we simple select it like we do for our normal JQuery pattern. If we want to only change the item the event is happening on (the thing we selected and put the event on) we use a special keyword this as the selector: $(this).dosomething(); Click.click(function(){ // do something when someone clicks on selector
Other Mouse Events // note each gets the function between parenthesis, I'm just leaving out.mouseenter();.mouseleave();.mousedown();.mouseup();.hover(); // special method to add a mouseenter and mouseleave event with an object $('something').hover(function(){ // do something on mouseenter }, function(){ // do something on mouseleave Submitting a form.submit(); $('#some-form').submit(function(e){ // this line stops the form from going to where the action sends it e.preventdefault(); // then you do things like select the values of the input Get the value of an input $('some-input').val();
Regular Javascript Even when using JQuery, you'll need to know a little plain javascript (the things that make up the javascript programming language) Variables Variables are just holders. Think of them as a cookie jar. You can put stuff in it, take it out, change what stuff is inside. Another metaphor is that they are the nouns. Variables are set with the var keyword, followed by a variable name (that you choose), then an equals sign, followed by a value, and finally a semicolon var myvar = "some value"; Note: Variable names should start with a letter. There should be no spaces or dashes. There are many types of content a variable can hold Numbers An integer (4) or a float (4.56) var myvar = 4; Strings Strings are characters ("e") or words ("Hello, world") Note they need to be in quotes (single or double, your choice may change if you have a word like you're in the text) var myvar = "Hello, World!"; Booleans True and false as keywords. All lowercase. var myvar = true; Arrays Arrays are comma separated lists. The values can be any variable type in this list (including arrays). They are written between brackets. var myvar = [4,"Hello, World!",true]; Arrays are index (number in the list) based and that index starts at 0. So, based on myvar above, if I said: myvar[0] It would be equal to 4. myvar[1] Would be equal to "Hello, World!"
Objects Objects are lists, but, unlike arrays, they are keyword based. You make up the keywords. Think of them a list of variables. Each value can be any type of variable (including objects). Objects are written between curly braces. var myvar = { mynumber : 4, mystring : "Hello, World!", mybool : true, myarray : [1,2,3] }; Objects are keyword based using one of two notations: myvar.mynumber Would equal 4 myvar["mystring"] Would equal "Hello, World!" Objects are imperative to understand for working with JQuery plugins. For many plugins you will call a method (defined by the plugin) on some wrapping element and pass in a setup object based on the plugins API. Functions Variables can be functions. They are examined below. Functions Functions are recipes. You shove in some ingredients, bake them in the function, and get out cookies. Ya, I know that metaphor was terrible. You don't necessarily have to pass in ingredients (known as parameters) and you don't necessarily get cookies (known as a return value). But you always are doing something inside the function. Another metaphor is that functions are verbs. Functions can be created with two methods: function myfunction(){ // do something } var myfunction = function(){ // do something };
Both examples above you would call (use) with: myfunction(); Inside the parenthesis you give extra inputs called parameters. Separate parameters with commas. Parameters can be values or variables. var myfunction = function(myvar,4,"hello, World!"){ // do something }; Parameters are so you can re-use a function. If we hard-code a value, there's not much we can do with it. But if we use a variable, we can pass in any number of values. Functions can also return a value using the return keyword. We might not use this a lot in this course, but it is a thing. Here's an example of how we'd really use this stuff: var myvar = 4; var myfunction = function(inputnumber){ var mynewvar = inputnumber + 10; return mynewvar; }; var myanswer = myfunction(myvar); In the above example, we create a new variable within the function (mynewvar). We use that to add 10 to the parameter we passed in. The parameter is called inputnumber. We pass in our own variable called myvar, which is like passing in the number 4. In the end, we spit out an answer of 14 and store it as the myanswer variable. Functions do not need to return anything and instead we can just do something as we do a lot in JQuery events. $("button").click(function(e){ // make it rain without a return // if you dare, use console.log(e); to see what is there Where does the "e" parameter come from? In JQuery events, a special event parameter is automatically created that you can use for various purposes. You don't need to call it e. It can be called anything, but it is standard to call it e or event. This parameter is an object of all the information about the HTML element you selected.
Other Useful Javascript Features Javascript has other things, but they are beyond the scope of this class and I will only teach you them if you need them/want to know them. Things include: Math Javascript can do math. Add, subtract, multiply, etc. Conditionals Sometimes we want to know if some condition is true or false and then decide what to do next. This is a job for conditionals such as if and if/else. For this, we rely on comparing things using comparators such as == (is equal to), >= (greater or equal to), < (less than), and others. Iteration We might want to loop through things and do stuff over and over. We can do a set number of loops or we can loop through an array or object. Communicate with a server Sometimes we want to send information from the website to the server or vice versa. This is called asynchronous communication. We don't need to refresh the web page to send these messages either way. Other Methods The javascript language provides a bunch of methods (pre-written functions) for doing things like getting a part of an array or string or telling us extra information about a variable. Every variable type has specific methods for finding out information or manipulating the variable.