JavaScript for Web Designers

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi I'm Edward Allah and in this course you'll learn JavaScript from a web designers point of view we'll start with the basics like variables data types and loops and we'll finish with more complex notions like functions selectors and events in the end we'll have a look at five common coding patterns using javascript with that said welcome to JavaScript for web designers let's begin hello and welcome to the first lesson of this course where you'll learn two things what is JavaScript and how to work with it let's begin javascript is a programming language and if you ever took a computer science class in high school or in college maybe you might have learned Pascal or C or C++ well those are also programming languages PHP is also a programming language now JavaScript can run locally in your browser and that's usually what it does but it can also run on a server using node.js a regardless of how you run it javascript is one of the three core technologies used to produce content for the world wide web the other two being of course HTML and CSS now every modern browser supports JavaScript by default he don't need any plugins to run it so that makes it a really good choice for adding a little bit of interactivity to your website or your web application and that's a very quick intro to JavaScript now how exactly do you run it when it comes to writing and running JavaScript code you can do it in three different ways the first way is in the browser console so I have Firefox here opened and this right here is the console and for example I can type stuff like alert I can specify message and hit that and I get an alert box or I can do a console log something else a different message and that will log to my console so this is a very quick way to check things for example check a variable value made me debug your code or do very simple operations so for example I can do stuff like five plus four and gives me nine I can do arithmetic operations I can do boolean operation so if I say one is higher than five and gives me false all sorts of stuff the second way is by writing it in line in your HTML document and first you can for example go to an element and say stuff like on click for example and type your JavaScript code so let's do an alert here and say it clicked then refresh and when I hit this gives me an alert or you can use script tags so script also adds this type text/javascript we can leave it but it's not necessary so you can just do script script and then inside you can type your JavaScript code so for example console.log 10 times 5 and that's going to give us 50 on the console finally the third way of running and writing and running JavaScript is by using a dedicated JavaScript file so for example I'm going to create a new file here called script J s and I'm gonna do a console log from here that says this is a log from a dedicated JS file and then we actually have to load that javascript file and we're gonna do it in the footer of our document we're gonna say script we're gonna delete this and we're gonna specify a source to script that is we're not gonna type anything inside the script only setting its SRC so now refresh and we have that log entry and these are the three methods you can use for writing JavaScript now for the upcoming lessons go ahead and pick the one that you feel most comfortable with personally I'm not a big fan of the first one because while it is good for quick checks and very simple things it's not very suitable for large blocks of code instead I'll be using the second and a third depending on the lesson in the next lesson you'll learn everything there is to know about variables I'll see you there welcome to lesson number 2 where you'll learn about variables now if you've ever worked with a CSS preprocessor like less or sass then you're already familiar with variables these store values of specific data types for example you can store numbers you can store strings of characters and so on so in JavaScript things are very similar to declare a variable that's where you start right you declare a variable and you do that with the keyword var now following this keyword var is the name of the variable or the identifier now you have to be careful when naming your variable because identifiers have specific rules they can contain letters digits underscores and dollar signs they must begin with the letter so for example if I do three or two followed by some letters that's not valid the names can also begin with a dollar sign and underscore but we're not going to use them in this tutorial and also names are case sensitive so Bob here is different than Bob with a capital B these are two different variables also remember that reserved keywords from JavaScript are also prohibited from being used as identifiers so for example if I do var var that's not correct because vore is a reserved keyword in JavaScript so let's something a simple variable let's say item and then we're gonna end that line if you want to define another variable you can do again var item 2 but you can also do it var item : and then item 2 now this right here is not a valid identifier because it has a space so either concatenate them like this or use an underscore now how do you set a value in a variable law after you defined the variables you can call them like this item equals and you can specify a value I'm gonna say five here and then item two equals two I'm gonna put a string I'm gonna say hello so now the variable item holds the value of five and the variable item 2 holds the value of hello and this is a string so how do you call these variables well very simply by their name or by their identifier so if I go back in our page here and I open up the console and I say item that's gonna print 5 if I say item two it's gonna print hello if I say item space too it's gonna give me a syntax error so that's the easiest way to work with variables now variables also have something that's called scope and scope refers to the context in which these variables are available if you define a variable like this the way I did it item item two they have a global scope which means they are available globally but as you'll find out in a later lesson you can also create a local scope inside for example a function or a specific block of code in that case that variable which has a local scope is only available within that function or that block of code but I'm just mentioning this right now we'll go into in more detail further down the line but that's about it for variables just a quick lesson now as I was saying in the beginning variables can hold multiple data types and we'll be learning about that in the next lesson see there hello and welcome to lesson number three of this course where you'll learn about the data types in Java Script and there are seven data types in total five of them are primary two are composite let's go ahead and start with the primary ones these are string number boolean null and undefined the string is basically a group of characters so you'll say for example var name equals John that's a string and it can use double quotes and you can also use single quotes but it's usually preferred to use double quotes the number data type would be something like this age 32 this is written without any kind of quotes if you would put 32 inside quotes it will then be treated as a string instead of a number now numbers can be either integers like this or floating points like this 32 point I don't know 12 that's a valid number the next type is bullying now boolean is a special type because it can only hold two values very different from the other two types it can be true or false so I can say something like married equals true or equals false the fourth primary data type is not now the null data type has a single value in JavaScript and that is not and it's usually used to erase the contents of a variable without deleting the variable itself all you have to do for example is set age to null an age will have no value whatsoever finally the undefined data type usually happens when you're trying to access an object properly that doesn't exist or you're trying to access a variable that has not been given a value so for example if I set a variable here called car model for example and I go back here and I say car model it's going to return undefined while if I say age it's gonna give him back null so see the difference between the two but if I say name it's gonna return John so those are the five primary data types now before we move on I just want to quickly show you something called type of now type of is an operator and you do something like this type of and it's followed by an operand so watch what happens if I say type of age type of age gives me an object but if I say type of name it's gonna give me a string let's try type of car model gives me undefined so what happens is when you're using the type of operator it's going to return the type or the data type of the operand so for example if I say type of false gives me a boolean if I say type of false in double quotes it's gonna give me a string so it's a very nice way of checking out the type of a variable and this can be used in lots of different ways for example when you're doing some operations between two variables and first you want to make sure that they have the same type to prevent errors now that's pretty much it for the primary data types the composite datatypes I mentioned earlier are arrays and objects there are two of them and we'll be learning about those in the next lesson hello and welcome to lesson number four where you'll learn about the first composite data type in JavaScript which is arrays now an array is basically a list of values and the way we can clear one is simply for let's call it list equals and we'll use square brackets and we can put in the list of values for example I can say in John Murray and we separate these by commas and Sander I can think of a better name there so this is an array which has three string items but you're not limited to string items you can have an array of bullying's or an array of numbers or you can mix and match so for example I can add another one here that says 32 or I can put another one here that says false right so this is a valid array now this is the first method of declaring an array you can also declare an array like this for example list two equals this this is an empty array but it's an array nonetheless or let's call this list three equals new array and here you can also specify its contents or for example 12 and false this is a valid syntax now this is how you declare an array but how do you access it well just like you would access any normal variable so if I go back in here and I say for example list it's going to give me my array jean-marie standard 32 and false or list two it's gonna give me an empty array or list three it's going to give me the third array that we've just created now this will give you the entire array but what if you want to access a specific element from that array well to do that you would say a list you open up square brackets and you specify a number from zero to whatever you want basically arrays are zero based index which means the first item sits on position zero the second item sits on position one and so on and so forth so if I say list zero it's gonna give me John if I say list two it's gonna give me the third item which is sand or if I say list five is gonna give me undefined now why is it giving me undefined all because our array has five elements so it it's element count only goes up to four zero one two three and four five items so if I specify an index this is what it's called if I specify an index that's larger than the the length of the array it's gonna give me undefined but if I say list for it's gonna give me the item on the fifth position now the way to access these arrays is the same regardless of how you define them in the first place either using the this syntax or using the new array syntax now arrays have properties and they have methods properties we're only going to talk about one and that is length and the length property gives you the number of items from that array the way to access that property is with the array name in our case let's do list dot length and list off length is going to give me five because I have five items list two dot length is gonna give me zero because it's an empty array and list three dot length is gonna give me two because we have two items in that array a very simple property you can use to find the number of items in an array now let's move on to the method because these are a bit more interesting the methods we're going to be talking or push pop shift unshift and index of the push method will add an item to the end of an array so I have my list array here and if I want to add another item I can just say list dot push and then in parenthesis I'm gonna put my item and that can be anything boolean number null string or whatever so I'm just gonna put a string I'm gonna say hi so now it gives me the new length of my array but and if I do list again I get the updated array so that's push pop will actually remove an item from the end of the array so I can say list dot pop make sure you use parentheses because this is a method and that give me the item that was removed from my list so if I read you you'll find that we now have an array with just five items the third method is called shift and it's used to remove an item from the front or the start of an array so if we do list shift it removed John as you can see John is now gone now to add to the front of an array you would use on shift so list on shift I'm gonna add ten here yes Annelle list is this bit finally index of is used to find the index of a specific item in an array so let's say for example that I want to find a position of the number 32 in my array so I can do a list index of 32 and that gives me 3 right so we have 0 1 2 & 3 but if I do index of this bit and actually it has been is not defined but if I do index of 32 32 gives me minus 1 and this is the value that's returned in case that item is not found in the array and that's pretty much it for arrays now coming up we'll talk about the second composite data type which is objects see there hello and welcome to lesson number five where we learn about objects now objects in JavaScript are I think pretty easy to understand and it all starts from properties a property is an association between a name and a value for example color equals red that's a property properties can also have functions has values in which case those properties are called methods but we'll come back to that now objects are collections of properties plain and simple so let's have a look at how you can create an object how you can access it and a lot of good stuff to create an object you start of course with a variable and let's call this a variable person and we're going to say new object that's one way to create it another way is to create let's say car equals curly brackets so just like arrays where you we used a square brackets to create them or the syntax new array objects we use new object and curly brackets instead of square brackets and what you can do now is start adding properties to these objects so for example person what could we want to know about that person we want to know its name its age maybe its height right so we can say person dot name equals let's say James person dot H equals I don't know 43 person dot height e equals one point seven six and actually this should be a number instead of a string and we can also say person that married he calls true so now if we type person in our terminal here we get an object with name age height married set to the values you just saw you can also access these properties in the following way person square brackets and then inside double quotes the name of the property person name equals let's change this to Kirk refresh and now if we bring a person it's gonna give me Kirk for its name and that's how you can access these properties and also how to change these properties both syntaxes are valid but probably the dot followed by the name of the property is the easiest one to use now you can use objects inside objects in the way that an object is the value for a property so for example if I add another property here called car or mmm-hmm let's not confuse it with this one here let's just delete this yeah so I'm gonna say person dot car equals a new object and then I can go and say person car dot make equals Honda for example right so now if I recall person it gives me this object and if I do person that car it gives you another object and if I do person car make it gives me Honda so this is how you can access these object properties even if they're embedded in now you can also define these properties when you first initialize an object so for example let's delete this and I can say four percent equals and I can specify it like this name are the age 30 notice the syntax here is a little bit different so now when I ask this person I get this object as I was saying in the beginning of objects can also have methods and a method is simply a property that has a function has its value but we didn't learn about functions just yet so there's no point in me talking about object methods right now what I gave you right here are the basics of objects how you can create them how you can use them how you can access their various properties and with objects we've actually completed all seven data types in JavaScript now coming up in the next lesson we'll learn about the available operators in JavaScript see there hi welcome to lesson number six where you'll learn about operators and there are a few different types let's begin with the assignment operator since this is the most basic now the assignment operator will basically assign a value to its left operand based on the value of its right operand and the simplest one is the equal operator so let's say for example that I have a variable x equals 1 we assign the value of 1 the right operand to X the left operand so now if I type X that's going to be equal to 1 I can also have a variable for example y equals 3 and then what I can do is say x equals y and now x will have the value of 3 so that's the basic form now there are also compound assignment operators for example the addition assignment that looks something like this x equals x plus y and that gives us 6 but I can also say X plus equal Y X plus equal Y is the same thing as x equals x plus y similar to these are subtraction multiplication division and a bunch of others but I'm just going to show you a few examples here so the subtraction will be X minus equal Y the multiplication is going to be X multiplied equal Y and the division will be X slash equal Y and just like the addition assignment you can already deduce their full form so for example the subtraction is x equals X minus y and that's a quick look at the assignment operator let's move on to the comparison and logical operators and the comparison operator will basically compare its operands and return a boolean value based on the result of that comparison so if the comparison is true it's going to return true if it's not it's going to return false now I'm sure you already know what the comparison operators are it's equal to its greater than smaller than greater than or equal to and so on and so forth so you see where I'm going here let's see if you a few examples so if I say X is higher than Y it's going to give me true because currently X is 6 Y is 3 but if I say X equal to Y it's going to give me false because those two values are not equal I can also say X not equal to Y and that's going to return true and there's also a strict equal that I want to show you real quick so if I say X strict equals so 3 equal signs why it's gonna give me false but if I set Y to 6 and then I repeat X strict equal Y it's going to give me true but what if I'm doing x equals 6 so instead of a number I'm assigning the string to the actually Y variable right then if I say x equals y it's gonna give me true because it's 6 and 6 but if I say X is strict equal Y it's going to give me false and that's because strict equals also considers the operand type if you do just is equal so two equal signs it's just going to compare the value while strip equal is going to look at it type as well now the logical operators are and or and not so and let's say for example x equals true and y equals false if i say x and y it's going to give me false because the end operator will return true if both operands are true otherwise it's going to return false if I do X excuse me X or Y it's going to give me true because the or logical operator will return true if either of the operands is true if both are false it's going to return false finally the logical not operator will basically switch things around so X is currently true but if I say not X it's going to return false and Y is currently false so if I say not Y it's going to give me true basically the not operator is gonna return false if it's operand can be converted to true otherwise it's gonna return true now let's talk about the arithmetic operators and you've already seen a few like + - these are arithmetic operators but there are a few that are a bit more special and I would like to show you those so first of all we're going to talk about the increment operator and this is a unary operator which means it only needs one operand it's not like for example the equal operator which needs two operands right so the increment operator basically will add one to its operand so for example if we set X to three and I say X plus plus and I read X after that it's going to give me four so what happens is X plus plus will first print X and then it's going to increment it by one if I do plus plus X it's gonna give me five because it's first going to increment it and then it's going to print it same goes with decrement also a unary operation instead of adding one to its operand it subtracts one so if I say X minus minus X is going to be equal to four and it also works the other way around - minus X now there is also a unary negation and unary plus and the yeren ocation basically will return the negation of its operand so X is currently 3 if I say minus X that's going to give me minus 3 the unary plus will actually attempt to convert its operand to a number if of course it's not already so for example plus 3 will give me 3 but if I have plus and the string of 3 it's gonna give me 3 it's gonna transform that type into a number if I say for example plus true it's gonna give me a 1 plus false is gonna give me 0 because 0 & 1 are considered false and true finally we're going to talk about the concatenation operator or the plus and that can be applied to a string so for example if we're gonna set some strings here for example x equals hello and Y is gonna equal 2 world right what I can do is say X plus y and that's going to give me hello world I can also do something like X plus equal and I can add another string to it for example hello again that's going to give me a hello hello and I can also do this 32 plus 32 32 is gonna give me that big string and that's a very quick look at operators in JavaScript now there is a programming concept that is I think is essential for any kind of JavaScript developer and that is the if-else statement again if you've done computer science in in school then you already know what that is but we're gonna cover that in the next lesson see there hello and welcome to lesson number seven where you'll learn about the if-else statement now and this is something essential for any kind of programmer and VFL statement allows you to execute various blocks of code if a specific condition is met so first let's have a look at the if statement so the syntax is very simple if we open some parentheses and in here we put a condition so let's begin by declaring a variable x equals 5 and it can say I can say if X equals 5 then we're going to do a console.log true and if I do a refresh I get a console.log of true now what happens here is first javascript evaluates this expression is X equal to 5 yes it is if true then we do the console lock so it's the same thing as saying if true it's going to have the same result or if 1 1 is also interpreted as true but if I say if x equals 251 for example nothing's going to happen because this condition is going to be evaluated it's going to be evaluated to false actually and the code inside the curly brackets is not going to be running well in that case we can specify else so if this condition is not met then we do this and I'm gonna say console.log false and you can actually chain these together right let's make a better example here let's say age of our age equals 20 24 right so we're gonna say if age is smaller then let's say 20 we're gonna log to the console teenager else if age is higher or equal than 20 and H equals smaller than 70 then we're gonna log a young man else we're gonna log not so young anymore so let's see what happens if I do a refresh tells me I'm a young man but if I change my age here to for example 70 tells me that I'm not so young anymore because 70 doesn't actually fall in these two categories if I would say smaller or equal than 70 it's gonna still say I'm a young man so this is how the if-else statement works now finally I want to show you another operator that's called the ternary operator or a conditional operator and that goes something like this this is actually a special case because it's the only javascript operator that takes three operands and let's do a simple law if-else I'm gonna say if age is higher than 20 then I'm gonna console.log not a teen anymore I'm gonna do else console.log teen now I'm just calling this bit okay so now tells me not a teen anymore well this I can actually compress to this age higher than 20 question mark console.log not a teen anymore : console.log teen and let's see it does exactly the same thing and this is the way it works the the expression here or the condition is evaluated and if it's true we're going to execute the code after the question mark if it's not true we're going to execute this code so a more simple version would be this condition Val one valve two so if this is true execute this otherwise execute this and that's how you can use the if-else statement now let's move on and talk about loops that's coming up next hello Anna welcome to lesson number eight where you learn about loops in JavaScript well loop is a piece of code that executes repeatedly either a set number of times or until the certain condition is met and if you've worked with sass and you've used the 4-h and wild directives then you already know what loops are all about now when it comes to JavaScript we have three types all three main types of loops we have the four we have the do-while and we have the while so let's begin with the for loop a for loop will repeat until a specified condition evaluates to false and we go something like this for we open in some parentheses then we'll have an initial expression now the initial expression can be or is mostly used to initialize a variable or a counter so for example I can say var x equals 1 and then I'm gonna do a semicolon and then follows the condition now the condition is the thing that's going to be evaluated and if that value of the condition is true then the loop will execute or the loop statement if the value is false then the loop terminates so for example let's say X is going to be smaller than 10 and I'm going to do a semicolon again and then third we have the incremental expression and this is usually used to increment the counter so I can say for example X plus plus and then we're going to open some curly braces and we're gonna have the main statement or the block of code that's going to be executed so let's say for example that I'm going to do a console log for X and that's going to be printing nine numbers in the column from one to nine now if I say X smaller or equal than ten it's gonna print ten of them because the condition evaluates to true when we reach number ten now if you're wondering well what can I use loops for well you can use them for a bunch of different things for example we have that names array what if we want to print all of the names in that array well we can do something very simple for example for var X or you can call it whatever you want y equals zero or starting from zero because an arrays index is zero based so we're gonna say Y is smaller then the names dot length y plus plus and then we simply do console.log names of Y and that's gonna print George Margaret and Shawn so what I did here I started from zero I'm going up until names dot length which in my case is three so we're going 0 1 & 2 or incrementing Y as we go along and we're outputting those names to the console next let's move on to the do-while statement and the do-while statement will repeat until a specific condition evaluates to false and a do-while statement looks something like this do and we'll have this statement here while and we'll type our condition so for example let's declare a variable here called x equals now it's actually delete the for yeah we're going to do VAR x 0 so we're going to do console.log names of X we're going to do X plus plus and we're going to do this while X is smaller than names not length and this will print George Margaret and Shawn but let me show you another example let's say that we have a while statement that looks something like this do console.log X while X is higher than zero and let's actually comment this bit and refresh it prints zero now why is this happening because X is zero so this condition here is not met well that's what do while does the statement is executed at least once regardless of how the condition is or to what the condition is evaluated to now on the flip side we have the wild statement which is very similar to this the only difference is the wild statement will execute or the while loop will execute the statement only if the condition is met so for example we have wild X higher than zero we're gonna console.log X and if we're gonna comment this and refresh we have nothing that statement console.log X has not been executed but if we do while consul while X is smaller than five and we do console.log X plus plus we're going to get this result that's the difference between do-while and a while now have you ever heard of mix-ins and CSS preprocessors well if you have then you should know that javascript in pretty much every programming language out there has something called functions and functions are very interesting very cool you can do lots of things with them and we'll learn about them in the next lesson hello and welcome to lesson number nine where it will talk about functions you can think about functions as sub programs that can have their own name can be called anytime they can receive parameters and they can also return values now to work with functions you must first declare the function and you do that with the keyword function then you would give that function a name so to give you a very simple example let's say print to console and then you would open parenthesis and in the parenthesis you can specify a list of parameters that it can then pass on to the function so let's for example say message here and you know all can open our curly brackets and then inside you would put the code that's going to be executed by the function let's do for example console log message right so then what I can do is say print a console and I can pass in hello and that's gonna print hello of course this is redundant because console log can already do this we don't need an extra function for that but I just wanted to show like what you can do with that function I can also do something like this I can for example function add and I can say value 1 value 2 I can do a console log of with l1 + l2 and in here I can pass for example I can say add 45 + 2 and that's gonna print for 7 to the console as I'm saying functions can also return values so for example instead of doing a console log here I can simply return valve 1 plus l2 and then what I can do is say console log add 45 + 2 and that's going to print the exact same thing so I'm basically saying console log I'm calling this function and passing in 45 + 2 and then I'm using the value that the function returns and I'm gonna print it to the console so that's how functions work really it's it's very very simple now functions can also be declared like this for example let's do the square of a number so we're going to say square equals function and we're gonna pass in a number and then we're simply going to return number multiplied by number so for example if we say console.log square 2 is gonna print out 4 now before we wrap things up with functions I want to talk about something that I mentioned when we talked about variables and that is a variable scope back then I said that variable scope means the context in which that variable is available and we have global variables and we have local variables so now that we got two functions I think this is a pretty good time to demonstrate that so for example let's say var X equals 3 now this is defined in the global scope it's not inside any kind of blockquote and that means the variable X is available anywhere so for example if I say a function test and I will simply do a console log of X and then I call it and let me actually clean this up a little bit here and then I call test that's going to print three now let's say I have another function here and we're gonna call this test two and it lets me clear a Y variable in here it's gonna be equal to five well if I'm gonna go into test and I'm gonna say console log Y it's kind of telling me that Y is not defined but if I do the exact same test and the test to function let's uncomment this and let's call test two it's gonna give me five so the variable Y is only available in the scope of this function it's not available anywhere else like the X variable which is global also let's do something like this we're gonna say var x equals 10 and we're going to do a console log of X here and also a console log of X here so first we are executing test and we're doing a console log of X and then we're doing a console log of X and the global scope so now if we refresh we have two values 10 and 3 even though the variable is called X it has different values in different scopes the global variable is called has the value of 3 and it's only available here and this X variable has a value of 10 so this console log actually prints this one not the global one and that's a very quick introduction to functions now as a web designer probably one of the main things you're using javascript for is to manipulate the Dom or the document object model essentially your web page and the easiest way to do that is with the help of selectors that's what we'll we'll be learning in the next lesson hello and welcome to lesson number 10 where it will talk about selectors now selectors are great they give you access to the Dom and allow you to manipulate it even and these selectors are tied really well into the document and window objects and if you remember from the objects lesson an object is a collection of properties basically properties and methods and by using these properties and methods you can gain access to various elements in your Dom and do various things with it now in this lesson I'm going to show you some of the some of the more popular or well-known selectors that you'll find yourself using as a web designer so the first thing I'm let's actually show you the page I have here it's a simple demo page we have some unordered lists a bunch of ID's on both of these we have four images all with a class of my IMG and each one with its different ID and then a couple of paragraphs now let's start with this so I'm going to do a console log for the document dot body let me actually open the inspector here right and this gives me body now body is an object and you can see all of its properties you can get a lot of information about this for example client height client with the inner text the inner HTML down here we have events we'll learn about those in next lesson but basically this is a very simple way to access these properties or document images for example document images is going to give you this HTML collection right so we have your images here and you can learn various properties for them like the base URI you can learn the alt the class name with height the SRC and so on so by having access to these you can actually start using selectors and manipulate them do various things with them so let's see a couple of examples let's say for example that I want to grab the very first item which is this item one hell exactly would you do this well we're gonna go right here and I'm gonna say this var first item equals we're gonna get the document object and we're gonna use the following method get element by ID and in here we're gonna put the ID of item - 1 because that's what we have in the Dom as you can see your ID item - 1 right so if we do a console.log for this first item it's gonna give us the item itself right so that's the first method that I want you to remember get element by ID it returns not the first element that it finds in the Dom with that particular ID now this will just return one element because if you want your HTML to be valid IDs are a unique so you cannot have two elements with the CMA with the same ID so that's why this method this function basically returns a single element okay now let's say that you want to get access to these two you l's right so they both have the class of my list well to get elements or the same class he would do document get elements plural by class name and we're gonna say my list yeah so now my list gives me these two unordered lists what about getting elements by their tag name which means get all the images all the paragraphs well that's also easy to do you can say for example paragraph equals document get elements by tag name P paragraph and that's gonna select these three paragraphs here now if you've use jQuery you remember how you would use selectors there you will do something very close to CSS selectors right well you have something similar in vanilla JavaScript and that's with a method called query selector all so for example let's say that I want to select all the images well I can just say images equals document dot query selector alt and I will pass in a CSS selector in my case it's IMG and that will select all the images okay so now you have all of these variables which reference objects in your or elements in your page how do you manipulate them well first of all you can start with the CSS properties by using the style property so you would say something like for example first item you would say style dot and then color and you change that to something else for example red so now the first item is red then what if you want to hide this second list well let's think about it my list is actually an array that's what get elements by class name returns so it's an array you're going to access it like this my list you're going to pass in an index I'm gonna say one because we have two items and it's a zero based index so we have zero and one so my list one style.display equals none and that will essentially hide my second list then let's say that I want to change the color of all of my paragraphs to green well we can actually use you can do it by hand or it can use a loop so for example we're gonna say for VAR i equals zero i smaller then oops smaller than paragraphs that length paragraphs not length works here because paragraphs is an array I plus plus we're gonna say paragraphs eye style color green so now all of these paragraphs are green and that's how you can manipulate the Dom using selectors and a loop now the list here can go on and on but these are the basics this is what most people use this is what will mostly be using how to access elements in your Dom and we're gonna leave it at this you're gonna see more complex examples when we get to the two demos at the end of this course now JavaScript also allows us to work with events and that's what we'll be learning in the next lesson see there hello and welcome to lesson number 11 where you learn about JavaScript events and actually JavaScript events is a bit improper because the events are happening on the HTML side all you can do in JavaScript is listen to these events and react accordingly now an event can be something triggered either by the browser like for example when the page has finished loading the browser triggers an event or when an image has finished downloading from the server then the browser triggers another event or they can be something triggered by the user like for example when you click a button now the list of events is like a mile long and we're not going to go through all of them is dead I'm just gonna pick four which are probably the ones that you're going to be using the most and I'm going to show you how to listen to these events and how to react to them and there are two ways you can listen to them either in HTML in line or in JavaScript with add event listener now the test page I have here is very simple we have a paragraph in a container and a button and of course clicking this button does nothing for now but what you can do is say on click and you can execute some JavaScript code so for example you can say something like console.log button clicked so now when I click the button I get a console log so that was a piece of JavaScript that you just executed this is the simplest way to tie into an event like click for example there are other events for example like onload on mouse-over on key up these are just a few examples now let me show you how to listen to these events from javascript or in or using javascript code so in my scripts file here I'm gonna declare some variables first submit BTN it's gonna be document get all on by ID submit and then I'm gonna target the container equals document I'm just gonna say query select your container now I'm gonna get the submit button and I'm gonna use the function add event listener it looks like this add event listener we're gonna pass in the name of the event that we want to listen to you in our case it's click and then we're gonna specify what happens when that event is being triggered and we can pass in a function name or we can declare an anonymous function here so we're gonna say function we're going to pass in the event parameter and then we're gonna say console.log hey i've been clicked I'm just gonna escape in this character right there okay so now if I click this we get two different console logs one is from the the unclick in the HTML and the second one is from the add event listener from JavaScript now let's see an example of another event for example mouse enter and let's say that when I enter with my mouse cursor in the container area I want to do something do a console log anything so I'm gonna say container add event listener we're going to passing the event name in our case it's mouse enter and the function name or the function that we want to execute in my case I'm gonna say Mouse enter container now this is a function that I'm gonna create right now so function Mouse enter container it does not receive any parameters but instead it does a console log that says hey there was a mouse over if a mouse enter event triggered so now whenever I take my cursor and I enter the boundaries of my container element I get that console.log you can see by the number here we already have 10 logs but let's say that I want to do this just once right so do the console.log just the first time the event is triggered well to do that I can simply do the console log and then remove the event listener so for it I can say container remove event listener mouse enter and then the name of the function so the syntax is exactly the same as add event listener but we change the name of the function here so now well I enter the boundaries of the container I get the console log but I only get it once all right let me show you another example real quick for the event key up right so we're gonna say documents add event listener key up function event now this is a great way to show you what that event is doing I'm to a console log event.keycode now event is an object as being transmitted to this function and you can access various properties for that object such as key code which is the the code of the key you just pressed so for example if I start typing you'll see that we get various codes if I do an enter we get the code 13 if I do this Cape I get 27 so this is a really great way to listen for key presses to give you an example of what you'll be using this for or what you could be using it for you make a slider an image slider and you would use the right and left arrow keys we can see there are codes pop up just right there 39:37 to switch slides right to move between slides that's one use for them but yeah basically that's about it for JavaScript events now you've learned the basics of JavaScript so it's time to put this knowledge to good use by creating some demos for some of the most common coding patterns in JavaScript and it will begin in the next lesson with a back to top button see there hi welcome to lesson number 12 this is the first of our five demos and in this lesson we're going to create a back to top button now I'm sure you've seen this around it's a very common pattern and the way this works basically you have a web page and when you scroll past a certain point you'll get a little back to top button somewhere on the page usually it's on the it's on the bottom part of the page and when you click it you're taken back up to to the top of the page so let's go ahead and see how we can create something like that using pure or vanilla JavaScript if you want now taking a look at the markup here we have a header with an idea of top we're going to use this ID to tell our script where we need to go back to then we have our main content with a bunch of paragraphs and finally a footer and in the footer we have an anchor tag with an idea of back to top this is our button as far as styling is concerned we just have some generic demo style here nothing nothing fancy really but what we're interested in is this back to top button right so its position is fixed so no matter how or no matter where we scroll it stays in the same position it's in the bottom right corner three ends from each side it's white with a point nine in the Alpha Channel it's at an inline block currently it has an opacity of zero so we cannot see it and we also have a class visible which gives it an opacity one so what we need to do basically is when we roll past a certain point in our page we're gonna add that class to the button making it visible and we also have to listen to the click event on the button and make our page scroll all the way back to the top now I'm going to write the script right here on the bottom of the page and I'm gonna start by defining some variables and then what we're gonna do is calculate the document height and we're gonna set the offset to 1/4 of that value and finally we're gonna add event listeners for scroll and click right now for variables we're going to target the the button so BTT back to top as a document and get all in my ID back to top then we're gonna get the body to document body duck elem that's gonna be document the document elements we'll be needing this one we calculate the height of our page then we're gonna set the offset to a hundred for example and two more variables will declare scroll position and dock height now let's calculate the document height we're gonna say duck height equals math dot max basically math dot max will take a bunch of values and it's going to return the the biggest one the maximum of those values and the reason we're doing this is because different browsers will look at a document height differently so for example Firefox is gonna have a different syntax to get the document height but WebKit is gonna have it down to one so just to make sure we we cover as much as many browsers as we need or doing this math max and we're gonna pass in the following values body dot scroll height body dot offset height doc LM client height and scroll height and finally we're going to get the set height now we'll do a quick check if the document height is different than undefined which means if math.max actually to return something which means if we actually have a a height value then we're gonna set the offset to dock height divided by 4 this value 100 is just a is just a fallback right in case dock height actually turns out undefined for some reason then we do have something to fall back on next up we're gonna add the scroll event listener and actually before that let's go ahead and do a quick refresh here and go to our console and call up call the offset and as you can see the offset is 7/3 7.5 now which means our script will be executed after we scroll past seven 37.5 now for the scroll event listener we're going to do window add event listener and we're gonna listen for scroll and we're gonna have a function we're gonna get the scroll position equals to body dot scroll top or in case that's not valid dock elem dot scroll top again this is for various browsers and then we're gonna say BTT class name equals two if the scroll position is higher than the offset then we're gonna add a class of visible oops sorry the other way around otherwise we're gonna add nothing so that's what we're doing here basically this is the ternary operator if you remember or the conditional operator we're checking if the scroll position is higher than the offset so basically if we passed that threshold when we scrolled we add the class of visible to the to the button to the BT T otherwise we add nothing to the class name okay so let's have a quick look refresh and let's see there it is so when we scroll yeah past that point we make the button visible and when we go back up or hiding it okay now let's actually make this button work so when we click it we want it to go to the very top so we're gonna say add click event listener BTT add event listener click again function event first thing we'll do is say event prevent default and that's to make sure that the button or in our case it's an anchor tag you know it doesn't go anywhere that's what this function is doing and then we're going to check if our browser is Firefox then we need to set the scroll top value in a different way so what are we going to do here is define another variable called is firefox and is firefox actually this is very very easy to do we've got to check for the navigator.useragent so let me actually I'm gonna say true here just so we have valid code but I want to open the inspector here and what I'm going to do is say navigator or dot user agent and navigator use agent is gonna give us this bit yeah and an easy way to check if this is Firefox well it says Firefox right here so all you got to do is compare that string to the word Firefox so is Firefox will be equal to the following navigator dot user agent dot we're going to use a method called to lowercase which will take a string it's going to make it a lowercase and then I'm gonna say index of Firefox is higher than minus one all right so if you don't understand what happened here let me tell you navigator.useragent will give us that string you saw in the console to lowercase is gonna make everything lowercase and then index of Firefox basically means at which position is the word Firefox in that string and if it returns a position that's higher than minus one it means the string the word Firefox is within that string otherwise it isn't there and this is a comparison so it returns true or false so coming back down here we're gonna say if is Firefox then we're gonna say doc Elam eh sorry scroll top equals zero otherwise we're gonna set body scroll top equals to zero so now refresh and when I'm down here I click the button it's gonna take me back to to the very top and now that I think of it I actually used I actually said in the beginning that we're gonna use this ID to bring us back to the top not really necessary to be honest because the way we're getting the top is we're setting this property scroll top equals zero so we might as well just get rid of this unless it has value in in styling which I don't really think it does you know it doesn't okay so we can actually get rid of this that's about it for our button now a small but interesting project is a textbox that supports Auto completion that will be demo number 2 and will be coming in the Nexus hello and welcome to lesson number 13 were will create a text box that supports auto completion now this can be used for lots and lots of different things but usually Auto completion is a feature that really helps out with the user experience when it comes to filling in forms right so imagine you have to fill in your country right and you start typing and it will be useful to you immediately as you type get a list of countries that match whatever it is you typed well this is what we're gonna create in this lesson so here we have our text box currently it doesn't do anything and coming back to the markup we see that it's very simple it's an input type text in a form it has an ID a placeholder and below that is in ul with an idea of autocomplete results this is the element that we're going to populate with the various results we're gonna get from auto completion so let's start our scripts file by declaring a couple of variables we're going to get our actual input we're gonna get the results and then we're gonna specify our country list and that's about it from now so let's actually document her step here next up we should focus the input when the page loads so we say target input dot focus and that yeah whenever we refresh now the cursor is always in there next up we have to add an event listener for the key up so whenever we press a key into the input we start comparing what we typed with what we have in our countries array we're gonna say target input add event listener on key up we execute the following function now before we move on we're gonna need some useful key codes here and these are 13 4 enter 38 our up 40 arrow down you'll see why we need these in just a little bit now we're gonna start by doing this results dot results plural dot innerhtml now all reset this so basically if there were results previously shown we're gonna remove those next we're gonna hide the results element and for that we're actually going to write a function to which we can just pass in a parameter and it's going to either show it or hide it and the function is called toggle results and we're gonna say height so let's go ahead and write that function and that function looks something like this so action is either show or hide and if the action is show then we're gonna get the results we're gonna add the class of visible otherwise if the action is hide we're gonna remove the class of visible very very simple now we're gonna say if this dot value the dot length is higher than 0 then so what exactly does the does this mean well this is an object and it refers to target input in this case so when we're doing this target input add event listener what can actually use this object to reference target input and it allows us to write code more elegantly and more efficiently so if the value that we typed in that input has a length that's higher than 0 which means if we type something basically then we're gonna do the following matches equals to yet matches this dot value now we have two unknowns here matches actually a variable that we need to define and it's an array so matches equals array and get matches is a function that we need to write and that function will actually compare the value that we just typed with all the items in the array and it's gonna return an array of the items that match the value that we just typed maybe it sounds a bit confusing but if you take a close look to the code you'll see that it's actually very very simple so let's go ahead and write that get matches function now that function looks something like this we're defining a match list array and then we're parsing the country list array which means we're going in a loop in a for loop from 0 to the last item and then we're checking if the item to lowercase index of input text to lowercase in protects being this bit so if the index of is different than minus 1 which means if the value that we typed in the textbox is contained within that particular item from the country array well in that case we're gonna do match list push that country list we're populating the match list array with that country's name and then we return match list so now coming back here we'll do this matches that length is higher than 0 which means if we have some country names returned by our function then we're gonna say this play matches matches now this play matches is a function that we're going to write now which will populate our autocomplete results and then show it so so what we're doing here basically is we're doing a while loop and we're going through the entire match list array every single item will be appended as a list item with a class of result to the results element which in our case is this e well then what we do is we toggle the results like this or we show the results so let's see if the works okay let's do a and you can already see that we have a few countries here Albania Colombia Cuba pretty much all the countries that contain the letter A if I do a L it shows me all the countries that have a and L he'll lay Nia Nepal Wales and so on and if I do L it just shows me Albania let's do another one let's do Nepal what do Romania so as you can see the script works beautifully now what I want to do is to have a little bit more control over that list when using my keyboard so for example I want to be able to move through my results with the up in air up and down arrow keys and then when I hit enter I want to fill my text box with that value so let's make that happen and we're going to start right here in our display matches function we're gonna say the first child gets a class of highlighted and for this we're going to say move move cursor or results cursor again two unknowns now a result cursor is a variable that we're going to initialize here that should be equal initially to zero and move cursor is a function that we're going to right now now the move cursor function will basically move that highlighted class up or down depending on which key I press so what we're doing is basically we're going through all of our results we're removing the class of highlighted from all of them and we're adding that one only on our position so now refresh you can see that when I type something the cursor or the highlight is on the very first item now let's see what we can do about when we press the up and down arrow keys and the place to write that code is right here in the KeyUp event listener so you're gonna say if results class list contains visible so if there are results that are being shown then we're going to do a switch and a switch is a much more elegant form of writing multiple if-else statements so we're gonna do switch and the criteria is going to be event dot key code and then I'm gonna say case thirteen we're gonna have our block of code and now we're gonna have break case 38 again block of code and then break and finally case forty same deal okay now what this means basically is check the event.keycode if it's thirteen execute the following if it's 38 execute the following and the same goes for 40 now this is where this comment comes in you can see that 13 means enter in which case I want to copy or I want to fill in my textbox with the value that I've just highlighted 38 and 40 arrow up and respectively down so in the case of an enter I want to do the following target input value equals results children results cursor inner HTML well results is our UL children means each individual list item a result cursor is the position that's highlighted and innerhtml basically means the text within that list item that's all there is really so we're taking this value and we're assigning it to the target input value so let's see that in action let's see let's type Romania if I hit enter you can see that the page refreshed there and that's because this is a form pressing enter in that form will automatically submit it and the page refreshes but we don't want that to prevent it we're gonna go right here and we're gonna add eventlistener for the input key down so we're gonna say target input add eventlistener key down function and we're gonna say if event.keycode equals 13 or if we pressed enter we're gonna say event dot prevent default and that if we type Romania again hit enter hmm some reason still doesn't work so what's going on here so add eventlistener key down for our function sorry I forgot to include the event here okay let's do a refresh so Romania hit enter and we now populate the textbox I was doing under test Albania enter okay but when I hit enter I want to actually hide this results element so here we're gonna say toggle results hide and also let's reset the cursor to 0 okay refresh let's try it again perfect all right now let's see about moving up and down in this list on 38 which is arrow up means we have to go up will simply say if we're cursor is higher than zero then will simply do result cursor - - and we're going to move the cursor to the new results cursor let's see Albania Harrow up okay let's actually do the arrow down first here we're going to say if results cursor is smaller then matches dot length -1 then we'll do a results cursor + + and move cursor results cursor ok let's do it again so now when we hit the arrow down key we can see that our cursor well apart from this pesky autocomplete thing from the browser but when we hit the up and down arrow keys you can see that we can cycle between our results and hitting enter on one of them we'll fill that into our text box and that's about it for this lesson it's time to move on to our third demo and I think that one's gonna be pretty popular because it is a Content slider so I'll see you in the next lesson hello and welcome to lesson number 14 for our third demo we'll have a look at a Content slider but we're not going to limit ourselves to just images as slides instead our slider can really take on any kind of slide text HTML whatever we can throw it now I'm gonna show you this slide is the finished one we just have some quotes here we have the next button the previous button and we can cycle through them like this when we are at the beginning the back button doesn't work and when we get to the end the forward button doesn't work so instead of wasting a lot of time writing this code essentially you can just open the source files that come with a course and then just copy the code from there I'm gonna walk you through the code I'm gonna explain why I did what I did and what's the purpose of each function and of each piece of code so first things first let's have a look at the markup here to understand what's going on so we have a container that has a slider container EUL with an idea of slider and each slide is basically a list item or the class of slide so we start by defining a couple of variables or getting the slides and we're getting the slider itself we're setting the cursor to zero now the cursor is gonna serve as a guide so that we know on which slide we are we're also defining slide with a top height top height will be used to find the height of the tallest slide slide count of course gives us the number of slides now if we have slides this is a check that we have to do then we're getting the slide with now why are we doing that because the way we're gonna organize things is we're gonna have the slides positioned absolutely and we're just going to offset them by their height so the the slide that's currently being viewed it's gonna be at left a zero but the slide before it is gonna be always gonna have the value left - the slide with the slide before that the same way and the slides after the current one are gonna have left the left value equal to plus the slide width so I'm actually show you that right here if we take a look at the inspector you're gonna see that our slides have a style set look this first one 4995 pixels and then we decrement like this until we get to zero which is the current slide but if I'm gonna hit back watch what happens with the left values now this slide is the current one it's left is at zero and the one that was before is at left 999 we do back again you'll notice that the value of the left property changes so how are we achieving that well we're setting the left value for each slide here so we're doing a loop and then on each slide we're setting its width times this counter plus pixel so if each slides with is one thousand pixels then the first slide is going to be one thousand times zero because the cursor is at zero so that will be 0 the next one is going to be at 1,000 the next one two thousand and so on then we calculate the tallest slide and calculate Oh last slide is a function that basically runs through all of our slides and it checks if the offset height of each slide is higher than the top height or the current top height then we're setting the top height to the height of that slide and then what we're doing is we're setting the height of the entire slider to that top height and we're doing this to ensure that all the slides are centered vertically and of course to do that we need to know the biggest slide next we're going to add the animated class to each slide and the animated class will basically allow for that smooth slide well slide is probably not not a good term here but the transition right so changing its left from zero to minus 1000 for example is made with a transition now why aren't we adding this from the beginning well if we did when we refresh the page all of the slides would just go flying on the screen because they would have that animated class so instead we're adding after all the elements have loaded then we're adding event listeners for next and previous buttons and we're checking if the cursor is smaller than the slide count minus one which means if we haven't reached the end we move the slides forward and we increase the cursor same thing for this bit only a reverse now move slides will take the direction so it's either forwards or backwards and what it's going to do is it will redo those left values right so the left values as you saw when I showed you the the inspector when you're moving a slide all of those values change let me show you again so when I hit the next button notice this slide here we're going to this second one so the first one gets a left of - 999 second one is zero next one is plus 999 and so on and that's what this code here is doing basically the replace that you see here basically has the role of stripping the value from the PX characters it's always doing and then we're adding slide with and then we're adding pixels again so that's it's compatible with this left property here finally we're adding an event listener for resize because when we resize our page the width of our slides will change because it's responsive so that means the left values will be rendered useless we have to calculate new ones and that's what we're doing here basically is we're recalculating those left values and the tallest slide and that's it really it's a very simple method of creating the slider and a responsive one at that it doesn't have any touch enabled features like when you're on a smartphone and you swipe it's going to change slide it doesn't have that instead it it just uses these two buttons now our fourth demo will be a image slider again a very popular javascript pattern that's being used in a lot of in a lot of webpages so we're gonna create that in the next lesson hello and welcome to lesson number 15 where we'll create a very simple image light box and a light box is usually an overlay that shows a much bigger version of a thumbnail essentially a larger image so here's the finished result we're gonna do the same thing as the previous I'm gonna show you the finished result I'm gonna show you the code and just walk you through it so we have a bunch of images here and when I click one of them we have this nice transition into a bigger version of that image and clicking anywhere will actually close that and return us to our original screen now the markup we basically have a ul or the class of gallery and each image has its SRC to a thumbnail and then data lightbox to the main image and at the end we have a divot an idea of lightbox overlay and this image element will be used to show the main or the bigger image now for the script and the script is actually very very simple here we just have one event listener click and we're listening on the document anywhere basically and we're triggering the lightbox click function so light box click gets the element that was clicked on gets the ID of the element gets the image that needs to display the larger version gets the lightbox overlay itself and it creates new image and this is actually another way of listening to click events so for example instead of of specifying which element we should listen for for click events we're doing document.addeventlistener click and then inside the function that's triggered we just filter the results like we do here so for example if the element we clicked on has the attribute of data lightbox that means if we clicked on one of those images then we know we have to open the overlay otherwise if we click on either the lightbox image which is the image that's being shown or the lightbox overlay then we're gonna close the lightbox or we're gonna remove the overlay and inside here so if we're clicking on one of the images on one of the thumbnails we're preventing the default behavior because we are dealing with anchor tags and then we're creating a new image and unload we're setting its SRC to the SRC of the image we clicked on then we remove the old source from the lightbox image and we're setting the source of the new image to the source of the image we clicked on so essentially when we're doing this bit we're triggering this function here and finally we're showing the lightbox and that's all there is to it really again a very very simple script just one event listener and we're doing two if statements or checking hey where exactly did you click did you click on one of those thumbnails fine it means we need to open a new image you clicked on anywhere else you clicked on the lightbox overlay or the lightbox lightbox image fine that means we have to close the overlay very very simple now the final demo we're gonna be looking at shows a very popular element and that is a tab control see you on the next lesson hi welcome to lesson number 16 where I'll show you how you can build a very simple tab control so this is the final result as you can see we have three tabs and clicking each one will toggle a different content now the mark-up is pretty straightforward we have a new L with a class of tabs that hold the links here on the top the active one has the class of active and then we have tab contents which refer to these right here each one has a an ID tab 1 2 3 and so on and the active one has a class of visible very simple now the scripts we do something similar to the previous demo were listening to click events on the document and then we're filtering them so if we clicked on an element whose href contains tab - then we move on otherwise we do nothing so if the H ref of the element basically will get the attribute of the element that has been clicked if it's not null and if it has tab - inside it then since we're dealing with links we're gonna prevent default behavior and we check if we didn't click on an active tab we switch tabs we remove the active class from all the tabs and all the tab contents and we simply add it to the one to the other one that we just clicked that's what this line of code here is doing now to actually show the tab content that corresponds to the tab on the top we get LM H ref Ella and LM H ref is basically the tref of the element we clicked so if we click on this first element the href is tab one so we're getting that by ID and we're gonna get to this item very very simple and we just add a class of visible so that's how we can create tabs as you can see very few lines of code and a very basic principle behind that was the final demo for this course please join me in the next lesson for the conclusion hi welcome to the conclusion lesson of this course I really hope you got a better understanding of what you can do with JavaScript as a web designer right and more importantly how to do that you saw some demos and those demos represent kind of a very popular elements that you will find and elements that at some point you might be required to create yourself now you might have downloaded various components like sliders and light boxes or maybe you've created some of your own with jQuery either way I encourage you to explore this side of it further see the kind of components that you usually use with jQuery see if you can code them using only vanilla JavaScript because most of the times we can do that with pretty much everything with that said I would like to thank you very much watching and from all of us at Utz + have a nice day bye you
Info
Channel: Envato Tuts+
Views: 199,817
Rating: undefined out of 5
Keywords: Web Design, JavaScript, design, web development, how to, web design trends, website design tutorial, how to create a website, web, how to build a website, how to design a website, website design, web design tutorial, graphic design, website, web designer, designer, coding, css, web designer career, JavaScript for Web Designers, javascript for web designers, information technology, responsive web design, web design, server side script, css tutorial, javascript tutorial
Id: ResWVWI333o
Channel Id: undefined
Length: 108min 20sec (6500 seconds)
Published: Fri Oct 20 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.