72. Conclusion
change the background color and the text now we could even use an eror function I have a preference for Arrow functions because they're concise with their syntax with an arrow function we have one parameter an event if youhave a single parameter you don't need to enclose it within a set of parentheses we have one parameter of event then do this do all this code and that should still work when I click on the box thecolor changes as well as the text so when you add an event listener you can pass in a call back or an anonymous function or an arrow function it depends on what your preferences are personally I like Arrowfunctions we have a few other Mouse events to discuss Mouse over and mouse out Mouse over is when you hover your cursor over something so let's take my box add a new event listener an element can have more
than one event listener add event listener we have an event and a call back as arguments the event is going to be Mouse over for the call back I'll use an arrow function we have one parameter of eventArrow do this let's copy these two lines of code I'll change the background color to be yellow like it's a warning and the text content to be don't do it that's a good face when I hover my cursorover this element the background color and the text is going to change the event that occurred is mouse over it's when you hover your cursor over something Mouse out is when you leave a specified element so when Ileave the box I would like to change back the background color and the text content We'll add an additional event listener my box add event listener the event type is going to be Mouse out then I'll write an
arrow function we're provided with an event Arrow do this let's change the background color and the text content I will revert the background color to be light green and the text to be click me whatever the text contentoriginally was when I hover my cursor over this element we get that Mouse over event but when I leave we get the mouse out event when I click on the this box we get the click event when Ileave the Box we get the mouse out event again to reset it essentially for the last part of this demonstration we're going to create a button when we click or interact with the button then we'll change a separateelement this box so within our HTML file let's create a button with text of Click me I will give this button a unique ID of my button and I'll increase the font size with CSS we will select my
button I will increase the font size to be 3 RM just so it's not so small let's select the ID of my button const my button equals document.getet element by ID my button I'll add the event listener to my button not my box if I was to interact with this button with the way it is now when I hover over the button we've created amouseover event and the button changes when I click on the button we're changing the HTML and CSS of the button because the button is what has the event listener we're selecting the target of the event to change whichis the button that is what we interacted with when we interact with our box it doesn't do anything it doesn't have any event listeners the button does though we're going to replace the event Target with my box whenwe interact with the button change the background color and the text content of my
box so then when I hover over the button the Box changes when I leave it reverts back to normal when I click on the button then we've created a click event all right everybody so that is an introductionto Mouse related events you'll need to add an event listener an event listener listens for specific events to create interactive web pages a few events we've covered include click Mouse over and mouse out to add an event listenertake an element use the built-in add event listener method pass in an event type and a call back Anonymous function or an arrow function to do something and well everybody those are Mouse related events in
JavaScript hey what's going on everybody in today's video I'm going to give you an introduction to key events in JavaScript so sit back relax and enjoy the show so what we've discussed in the previous topic is event listenersan event listener can be added to an HTML element they will listen for specific events to create interactive web pages we'll be discussing key down and key up there is a third type of key event called key presshowever according to the official documentation this event isn't compatible with all web browsers so you should avoid using key press a key down event occurs when you press down on a key a key event occurs when you releasea key by adding an event listener to the Dom document we can detect when we press down or release a key here's how we will access our Dom then add an event listener add event listener we have two
arguments the event type and a call back when we press down on a key let's do something doesn't matter what key it is any key for this next argument I can either pass in a call back an anonymousfunction or an arrow function I like Arrow functions so I'm going to use an arrow function we're provided with an event parameter when something happens within our web browser an event object is created we can access it soI'm going to console.log this event object and we'll see the details of it be sure to select your web browser I'm going to press the q key then let's go to inspect console and here's that event the webbrowser provided us with a keyboard event the key pressed was Q there's a relevant key code of 81 and there's other properties too like was the ALT key being held down at the time it wasn't same thing with
the shift key and the target which is the body of our document I'm going to Output the key property of the event we'll press a different key I'm going to hold down the F key I'm not releasing itI'm holding it down we're going to consistently fire key down events I would like to detect when I release a key I will use the key up event so let's copy this paste it the event is going tobe key up I'll display something else I'm going to use a template string I will display key down equals then I will display this events key let's do this with key key up too I'll just copy this keyup equals event.key let's go back to our console I'm going to hold down the S key then when I release it we'll have a key up event key up equals s oh one more important thing the arrow keys we have
Arrow up arrow down arrow left and arrow right if you ever would like to make some sort of game the arrow keys are also accessible now what we'll do on key down and key up is change an HTMLelement so to make this simple within our HTML document I'm going to create a div element this div element will have an ID of my box I'll add some text an emoji all right let's add a little bitof CSS we will select my box I will set the background color to be light blue we haven't picked light blue yet I will set a width of 200 pixels a height of 200 pixels a font size of7.5 RM I'll use flex box display Flex justify content
Center aine item Center this part is important for the next exercise we are going to set the position to relative for relative positioning I'll set the body of my document to have no margin margin zero all right weare ready we are going to select the ID of my box const my box equals document .getet element by ID the ID that I'm going to select is mybox when I press a key down I'm going to change the text content of my box mybox do textcontent equals I'll pick a different Emoji let's do that one and I'll change the CSS mybox dostyle do background colorequals tomato or some other color of you're choosing so when I press down on any key the HTML and CSS is going to change I'm going to release that key but we don't revert back to normal our HTML
element stays that way what we'll do is that when we release a key we'll revert these changes by going back to the original so let's take my box change the text content to equal an emoji because I likeemojis we'll use the original one then I will set the background color to be light blue now if I were to hold down a button the HTML and CSS is going to change until I release that button whichI am about to now in 3 2 1 go I'm going to try and press the space bar as fast as I can seizure warning let's go okay it's about time we move on what we're going to donow is using the arrow keys move this element we're going to create a const of move amount when pressing an arrow key how far do we want to move this element let's say 10 for 10 pixels I will
create a variable for X think of these as coordinates I will set that to be zero and y y will also be zero X for any horizontal movement and Y for any vertical movement document.addevent listener when we have a key down event I would like to do something I'll write an arrow function we're provided with an event do all this code I only want to do something if a user uses anarrow key so if I was to console.log my event then access the key property let's go to inspect console select your document I would like to do something only if the key pressed is Arrow up arrow down arrowleft or Arrow right I don't want any of the other keys I can write the if statement if access our event access its key follow this with the starts with method does this key start with arrow will only
enter the SI statement if the key of the event is Arrow up Arrow down arrow left or Arrow right then we'll write a switch we haven't written any switches for a while we will examine the key of ourevent with switches we examine a value against matching cases if we have a case of Arrow up if the key of our event matches the case of Arrow up then do this we'll take our y-coordinate subtract our movementamount which is 10 Yus equals the movement amount and then be sure to break to break out of the switch then we need a case for arrow down arrow down y+ equals our movement amount Arrow
left Arrow left X for the horizontal axis minus equals the movement amount and then Arrow right arrow right X plus equals the movement amount then outside of the switch but within our if statement we're going to access mybox access the style access the top property set it equal to a template string we're going to take our variable of Y for the y-coordinate then add pixels take the top property of my box set it equal tothe y coordinate we're going to copy this and do this with the left property set it equal to X in pixels be sure to select the body of your document we can move right with the right arrow keydown left and up or diagonal if I hit two keys at once the arrow keys have a default Behavior to scroll you can see that if we go down too far we have a scroll bar on the right
hand side we can prevent the default behavior of a key we just have to add this line of code take our event then follow it with the prevent default method so when my element Scrolls off screen it'll disappearwe're not going to scroll with it
to increase the distance in which this element moves we can increase the move amount let's set it to be 100 now we're moving a lot further with each key press hey this is bro from the future there's onemore thing I would like to add to this project when pressing down on a key let's change the text content and the background color much like what we did with the first exercise then when we release a keywe'll revert the HTML and the CSS back to normal we're combining the first exercise and the second one and this is the result when I move the arrow keys this guy's going to freak out until I Let
Go pretty exciting all right everybody so that is an introduction to key events in JavaScript you're going to add an event listener to the document when you select your document and press a key when the key is presseddown that will create a key down event when you release a key that creates key up event and well everybody that is an introduction to key events in
JavaScript hey everybody in today's video I'm going to show you how we can show and hide an HTML element using JavaScript in this video you'll need an image to work with once you find your image add it toyour website folder then we are ready to begin we're going to create a button and an image element let's start with the button the text on the button will be initially hide to hide an element I will givethis button a unique ID of my button I'll add a break then we'll create an image element this is a self-closing tag with this image I will set the source equal to either the relative file path or thefile name so my file is car.jpg it's a little too big I'll set the width attribute to be like 400 pixels that's a decent size I will give this image a unique ID of my image my IMG and
just so we can see this button I'm going to apply a little bit of CSS to the button let's select the ID of my button take the font size I will set it to be 2 RM that's decentenough all right let's go to our J Javascript file I'm going to create a reference to my button and my image let's start with the button const my button equals document.getet element by ID the ID that I'm selecting is my button let's create a reference to my image as well my IMG the ID was my IMG when I click on this button I would like to do somethingwe will take my button and add an event listener add event listener there are two arguments an event type and a call back to a function the event type is going to be click when we click on the
button we're going to do something for the call back we'll write an arrow function we are provided with an event parameter by the web browser Arrow do this when when we click on the button what code do wewant to perform we're going to take my image access its style access its display property set it to be a string of none so when you click on the button it's going to hide the image the display propertyis set to none not only that let's change the text on the button after we hide the element let's take my button change the text content equal to be show because now I want to show the element sohide become show when we click on the button a second time nothing happens we would like to toggle between hiding and displaying this element we'll write an if statement let's check to see if the display of my image
is strictly equal to none is the display of my image currently none if so we're going to set the display to Black block because it's a block level element take my image access its style access its display propertyset it to be block then within an lse statement place these two lines of
code and we will change the text content of my button to be hide now when clicking the button we can toggle between hiding and showing this element the image now let me demonstrate something if we were to takemy button then add it after the image here's what would happen let me add a break too so by setting the display To None we don't Reserve any space for that image my button moves up near the topof the window until I show it again another option if we would like to reserve some space for the image is to toggle the visibility not the display property replace display with
visibility we're going to check if the visibility is hidden set the visibility equal to be hidden if we would like to show the image the visibility is going to be set to visible when we toggle the VIS ilityof this image we at least reserve the space for it the elements that come after aren't going to shift near the top of the window you can use visibility or display depending on the project you're creating all righteverybody so that is how to show and hide HTML elements using
JavaScript so uh yeah I should probably talk about nod lists today a no list in JavaScript is a static collection of HTML elements they can be created by using query selector all we can select Elements by an IDa class or an element type nod lists are similar to an array but they don't have a built-in map filter or reduce method they do have a for each method at least though an important thing to note withnode lists is that they won't update automatically to reflect changes to the Dom for example if you were to remove an element from the Dom and it's within a node list you would also have to separately remove thatelement from the node list so what we'll do in this example is create four buttons they'll all have the same class we'll have button one with a class of I don't know what's a good name my buttons the
class all right let's copy this button paste it three additional times we'll have button two button three button four and I'm going to add a little bit of CSS to these buttons let's select the class of my buttonsI'll increase the font size so you can see it font size for RM add a little bit of margin 10 pixels remove the border border none smooth the corners with border radius 5 pixels add some padding 10 pixelsby 15 pixels I'll change the background color to something blue background color blue but I'll select hsl values I'll turn the lightness to like 60 okay that's decent and the font color will be white okay that's good enoughfor now one way in which we can create a node list is by using query selector all we've talked about this in a previous video but I'll show you a few more advanced things we can do with node
lists we can select Elements by an ID a class or an element type we will create a node list of let buttons equals document.query selector all let's select all elements by a class we need to use dot then the class name my buttons we could select Elements by an element type if I would like to select all buttons I would justtype in button the element type but I would like to select only elements by this class now that we have our node list I am going to console.log my node list of buttons and we'll take a look atit here's my node list it contains four elements button one button two button three button four we do have a length property a few methods entries for each item Keys these are all different methods for each is whatwe're going to be using a lot here's how we can change the HTML and CSS properties of all elements within a node list we can use the for each method of a node list and iterate through all of
the elements so we will take our node list of buttons use the built-in for each method then write an arrow function we are provided with an element Arrow do something but I'm going to rename element as button justso it's more easily understandable during each iteration we're provided with a current button what would we like to do to that button well let's change the background color button.style do background color I'll set it to be green that should update the color of all the buttons not just one of them we're iterating through all of the buttons within this no list change all of their backgroundcolors to be green let's change the text content too take each button access the text content I will set it equal to be I don't know an emoji or something let's do that the text content and all the
buttons is is going to change maybe let's append an emoji not replace the text content that's better that is how you can add and change HTML and CSS properties with a node list use the for each method thenwrite an arrow function to do something in a similar way we're going to add an event listener to each button that will listen for a click so again we're going to take our node list of buttons use thebuil-in for each method for each button Arrow do this we need to add an event listener to each button we will take the parameter of button add an event listener within our event listener we have an event typeand a call back to do something the event type is going to be click instead of a call back we'll write an arrow function we are provided with an event Arrow do this event is proved provided to us
through the web browser when something happens we will access the event objects Target meaning the button that we click on that's going to be our Target access the style access the background color property let's set it to bered or better yet tomato because I like tomatoes each button has an event listener it will listen for click events when we click on a button the background color is going to change we're going to add an eventlistener for Mouse over and mouse out let's begin with mouse over again take our node list of buttons use the for each method for each button Arrow do this take that button add an event
listener with event listeners we have an event type and a call back the event type Tye is going to be Mouse over when we hover our cursor over something what would we like to do we will write anarrow function event Arrow do this let's access the events Target that should equal our button that we click on access the style access the background color so with the current color I'm going to go back to my CSSI will copy this color paste it but make the lightness 10% darker now when we hover over one of the buttons the background color is going to change I'll set the lightness to like 40% to make it muchmore apparent there that's better now when I leave one of these buttons I need to revert that color back to the original really we can just copy all this code replace Mouse over with mouse out and set the
background color back to the original
each button now has a mouse over and mouse out event listener here's how you can add an element to a node list I will create a new button const new button equals document.create element what element are we creating a button so with creating an appending HTML elements there's three steps this is step one we need to create that element first step two is to add any necessary attributes or cssproperties so let's take our new button change the text content of the button equal to be button 5 I would like to give my new button a class of my buttons we're going to access the class list propertynew button.class list when working with an element's class we work with class list not class so the class list equals the class of my buttons then we have step three now we have to append this element to the Dom
what is the parent element of this new button going to be well in this case it's going to be the body of my document we're going to be adding a new button right here the parent the enclosing elementis the body in this case access our document select the body append Child new button and there's button five since we added our class of my buttons that's why it has all these CSS properties if I were toremove this line of code we get the default appearance for a button I'll talk more about class lists in the next video there's a lot you can do with them now if I was to console.log my node listof buttons here's what we have we have five buttons within our Dom but within our node list we have fourbuttons button one 2 3 four button five isn't within this no list no lists are a static collection they won't update automatically to reflect changes to the Dom even though button five is within the Dom we would need
to manually add it to our no list if we want to work with it so to do that we can just use Query selector again and select all elements by the class so let's reassign buttons since we're reassigningbuttons that's why I declared buttons with let instead of const so we're able to reassign it because if this was a constant we couldn't change the elements within it so buttons equals document.query selector all select All Elements by a class class my buttons and then again let's console.log my node list of buttons inspect console and there we go our node list has five elements button 1 2 3 4 5even if you were to add an element to the Dom that same element isn't going to be automatically added to your node list I would recommend using query selector all again just to update it here's how to remove
an element from a node list when you click on it we'll have to give all of these buttons an event listener they will listen for a click event when we click on one of these elements remove it fromthe Dom and the node list here's how again we will take our node list of buttons use the built-in for each method for each button within our node list do this take each button add an event listener weare provided with an event type and a call back to a function the event type that we're listening for is click the call back is going to be an arrow function we're provided with an event Arrow do thisto remove an element from the Dom when you click on it we will access our event object access the target use the built-in remove method to remove it so let's see if this works currently let's remove button 2
1 4 3 so those buttons are gone but let me show you something I'm going to console.log my node list of buttons after each
click even if I were to remove these buttons from the Dom they're still within the node list even after all the buttons are gone our node list still has four buttons so we do have to update that manuallyhere's an easy way how to do that we're going to use Query selector all again we'll reassign buttons equals document.query selector all select all elements from the Dom that have a class of my buttons then just to see if this works let's console.log my node list ofbuttons now when we click on a button it should be removed from the Dom and the node list when I remove all the buttons our no list is then empty all right everybody so that is an introduction tonode lists they're a static collection of HTML elements they can be created by using query selector all we can select Elements by an ID a class or an element type they're similar to an array but there's no map
filter or reduce method and do remember that nod list won't update automatically to reflect changes to the Dom and well everybody that is an introduction to node lists in
JavaScript hey everybody so in today's video I got to explain class lists in JavaScript class list is an element property it's used to interact with an elements list of classes meaning CSS classes by accessing the class list propertyof an element we can make reusable classes for many elements across your web page if I have a CSS class I can dynamically add remove toggle replace or check to see if an element contains a certain class sowhat we'll do in this example in our HTML document is create a button the button will have text of my button the ID of this button will be my button we'll apply a little bit of CSS initially let'sselect the ID of my button we'll be applying just a few properties let's increase the font size to for RM oh not 43 four go back go back go back I'll add a little bit of margin of 10
pixels remove the border with border none border radius to smooth the corners 5 pixels and add a little bit of padding 10 pixels by 15 pixels that's good enough for now we're going to create a CSS class ofenabled we won't apply it right away though we'll apply this class to this button using JavaScript if an element is enabled let's change the background color to be something blue I'm going to use hsl valuesthough and I will set the font color to be white so this button doesn't doesn't have this class yet we'll add that in dynamically using JavaScript we'll create a reference to this button const my button will be thename then we need to select it document.getet element by ID the ID that I'm selecting is my button to add a class to an element take that element my button access the class list property follow this with the add method we will add the name
name of the class enabled and now my button is enabled we have appended the CSS properties dynamically so if I were to inspect this element I'll rightclickinspect we have added that class of enabled to the element so my button has an ID and a class of enabled to remove a class again take that element of my button access the class list we will usethe remove method method we will remove the class of enabled and it's gone let's right click on the element inspect so our class list is empty we have added and then removed that class of enabled we're going tocreate a new class now of hover when we hover over an element apply these CSS properties it's kind of like we're using the hover sudo class but we're using it a little bit different we can add or removethis class dynamically at will if we apply this class let's set a box Shadow to give the element a 3D pop effect for a horizontal and vertical offset let's set those to be zero each let's add 10 pixels
for the blur effect and I will set the color to be I don't know let's set it to be black but set the alpha down to like 20% and then when I hover I would also like to setthe font weight of that element to be bold let's add the hover class so the appearance of this button changed I would like to apply this class of hover only when I hover my cursor over the element We'lladd a mouse over event listener we will take my button add event listener we have an event type and a call back to a function the event type will be Mouse over when we Mouse over this element weare provided with an element object event Arrow do this we will access our event objects Target meaning the button take our class list and add the class of hover and let's see if this works if I hover my
cursor over the button we apply the hover class now when I leave the button I would like to remove it really we can just copy the code for the event listener paste it replace Mouse over with mouse outthen we will remove that class so now we can apply that class and then remove it with mouse over and mouse out there's also toggle if we toggle a class we'll remove it if that class is present addthat class if it's not so let's replace add with toggle do this for both Mouse over and mouse out and that should work the same when we hover our cursor over the button we will toggle the class ofhover if we have a mouse out event we will toggle it again to removeit now we're going to use the replace method to replace one class with another we'll create a new class of disabled we'll be replacing the enabled class with the disabled class when we click on the button so with
the background color of the disabled class let's set the background color to be Gray again I like using hsl for the colors I'll set the lightness to be like 60% I'm trying to get a faded appearance and forthe color let's pick a light shade of gray using hsl values I'll set the lightness to be 80% going back to our Javascript file let's add the class of enabled my button access the class list use the addmethod we will add the class of enabled then we'll add an event listener to the button we will take my button add an event listener we have an event and a call back the event is going to beclick I would like to do something when we click on the button we will receive an event Arrow do this take our events Target access the class list we will will use the replace method replace the old class
with the new class replace the enabled class with the disabled class there's two arguments the old class and the new class replace the old class with the new class then when we click on this button we'll replace theenabled class with the disabled class then we have the contains method if an element contains a class this will return true and if it doesn't it returns false So within our event listener let's add an if statement andan else statement we'll check to see if our events Target access the class list we will use the contains method if we click on the button and the class contains disabled what do we want to do does theclass list contain disabled let's change the text content take our vents Target access the text content I'll append an emoji what's a good one that one else replace enabled with disabled let's click on the button we'll replace the
enabled class with the disabled class our button is now disabled if I were to inspect this element the class is now disabled if I were to click on this button again well our class contains disabled that was trueso we end up doing this code where we append to the text content of the button now the nice thing about using class lists HTML elements have a class list property we can reuse CSS classes amongst many HTMLelements we'll create an H1 element now the text of this element will be hello I will give this element a unique ID of my H1 I'll increase the font size so we can see it select the ID ofmy H1 I'll increase the font size let's try fiveRM let's create a reference to my H1 const myh1 equals document.getet element by ID the ID that I'm selecting is my H1 we'll add the enabled class to myh1 myh1 do classlist do add not ass add enabled and there we go we have added these CSS properties to this
element and because I'm lazy I'm going to copy all this code where we add an event listener to my H1 so let's replace my button with my H1 now when we click on this H1 element we can disableit we'll replace the enabled class with the disabled class and if you don't believe me let's take a look the class of my H1 is now disabled if I were to click on this element again while the classlist contains disabled so we execute this if statement where we change the text content of that Target now here's a challenge round we're going to create four buttons and store all of those buttons with then a node listso let's create a button with the text of the first button being button one I will give this button a class of my buttons let's copy this button paste it three times button one button two button three button
four let's remove the CSS from my H1 select the class of my buttons keep these three classes of enable hover and disabled okay let's eliminate all this code we'll create a node list to contain all these buttons wecan use const if we don't plan on adding or removing buttons or let if we do let buttons equals document.query selector all select all elements that have a class of my buttons we'll apply our enabled class to all the buttons so we will take our node list of buttons use the for each method for each button withinour node list do this take each button access each button's class list property I will add a class of enabled and we have applied that class to all the buttons If you need to remove a class you cando the same but replace add with removemove now when we hover a cursor over one of these buttons we will toggle the hover class we need to iterate through our node list of buttons take buttons use the built-in for each method for each button within
our node list do this take each button add an event listener the event listener has an event type and a call back to a function the event type will be Mouse over when we hover a cursor over itwe will be provided with an event argument Arrow do this access the event object access the target meaning the button that we hover over access the class list property we will toggle the hover class so when we hoverour cursor over one of these elements we will apply the hover class
now when our cursor leaves one of these elements we would like to toggle that class again let's copy everything we have here paste it replace Mouse over with mouse out when we leave one of these elements toggle thehover class again to remove thatclass now when we click on one of the buttons we're going to replace the enabled class with the disabled class take our node list of buttons use the for each method with each button Arrow do this take eachbutton add an eventlistener we need to select the event type and a call back to a function the event type is going to be click the parameter is event Arrow do this when we click on one of these buttons we'll replacethe enabled class with the disabled class take our event object access its Target access the class list property we will replace replace the old class with the new class replace the enabled class with the disabled class and let's
see if this works when I click on a button we'll replace the enabled class with the disabled classthe last thing we'll do is that when we click on a button that's disabled we'll change the text content we'll have to use the contains method So within our event listener I'll add an if statement if access ourevent access its Target access the class list property use the contains method does the class list contain the class of disabled if it does we'll access our event access the target of that event change the text content ofthat element I'll append an emoji that one I like that emoji if the class list of that element isn't disabled it doesn't contain the class of disabled we'll execute an L statement where we disable it by replacing theenabled class with the disabled class we have three event listeners Mouse over Mouse out and click we're utilizing all three of these custom classes enabled hover and disabled we can hover over these elements then we'll have Mouse over
and mouse out events then when I click on one of these buttons we can apply that disabled class within our click event listener we have an if statement if we click on an element that's already disabled append thetextcontent all right everybody so that is the class list property it's used to interact with an elements list of classes their CSS classes they allow you to make reusable classes for many elements across your web page and welleverybody that is the class list property in
JavaScript hey what's going on everybody in today's video we're going to create a game of rock paper scissors using JavaScript so sit back relax and enjoy the show all right let's do this thing we're going to create anH1 heading with text of rock paper scissors for a title we'll create three buttons the first one will be for rock you can add some text of rock but you know what I like using emojis I'm going touse an emoji instead I would like an emoji of a fist and I'm going to zoom in until we add some CSS let's create a button for paper that'll work and scissors maybe a p sign with each ofthese buttons I will set the onclick event handler equal to a JavaScript function we'll name the function play game now with these functions we're going to pass in an argument the first will be a string of rock now
if you use double quotes HTML is going to be confused where this event handler ends our argument is going to be a string but it's going to be within single quotes because we're already using double quotes let's copythis attribute cuz I don't feel like typing it again the second argument will be for a string of paper and thenscissors let's enclose our buttons within a div element this div element will have an ID of choices let's cut our buttons and paste them within the div element outside of the div element we'll create create another div elementwe will display the Player's Choice player colon space the ID of this development will be player display this will display the word rock paper or scissors depending on which button we pick let's do this for computer text willbe computer ID computer display we should display a result who won
the ID will be result display just for some temporary text I'm going to add it's a tie when we style this with CSS I would like to be able to see the updates we'll get rid of this prettysoon eventually we'll add in a score tracker but we'll do that after our game is at least working okay let's head to our CSS stylesheet I'm going to zoom back to 100%let's select the body of our document I will set the font family to be aial with the backup of s serif let's set the font weight to be bold throughout thisapplication I will set any margin to be zero around the body use flex box to display the elements display Flex the flex direction will be a column
and align itemsCenter let's select our H1 element I need to increase the font size font size 3.5 RM for a color pick acolor for me I'll set the lightness to 20% now we're going to select our development of choices actually let's make this a class class choices select the class of choices add margin bottom of 30pixels within this development we need to select all the buttons we will select the class of choices select all buttons within this class we increase the font size to 7.5 RM these buttons need to be big I willset a minimum width of 160 pixels at a little bit of margin between each button zero pixels on the top and bottom 10 pixels on the sides for the buttons I would like rounded Corners I would like thesebuttons to be a circle I can set the Border radius to something massive like 250 pixels that will give us some rounded buttons and pick a background color background color I want something blue I've already pre-picked a color
so I'm going to usethis now when I hover my cursor over one of the buttons I would like my cursor to change into a pointer and that does work let's also add a transition effect let's change the background color to e afterhalf a second let's access the hover sudo class of all the buttons of choices take the background color I'll set the lightness to be 20% lighter each button is going to light up when you hover your cursor overthe button then we'll work on the display displays next we're going to select the player display and the computer display these are ideas player display and computer
display let's set the font size to be a 2.5 RM and for the result display where it says it's a tie that's the ID of result display set the font size to be 5 R and I'll add somemargin to the top and bottom 30 pixels to the top and bottom zero on the sides okay that is good enough for now so we no longer need this placeholder for the result display let's add some functionality wehave a lot of constants to declare const choices choices will be an array of strings we'll have Rock paper and scissors we need to get the player display and the computer display so we can update them const playerdisplay equals document.getet element by ID the ID that I'm selecting is player display then we have computerdisplay computer displayand a result display this one it's empty currently const result display equals document.
getet element by ID result display we'll factor in scoring later we need a function of play game that accepts one argument the Player's Choice function play game we have one parameter player choice when we play a new gamewe have to pick a choice for the computer between rock paper or scissors what we could do is generate a random number between zero and two rock is index zero paper is index one scissors is index 2 we'llcreate a constant within play game of computer Choice I'm declaring it within the function so we can update it every time we play a new game equals take our array of choices at index for the index we'll generatethat random number using the random method of math math.random method * 3 then we need to round it because it's not going to be a whole number math.
floor to round it down so the computer's choice will be a random index between 0 through two which will give us randomly either rock paper or scissors hey this is bro from the future one thing that would begood for us to do is along the way use console.log just to be sure that what we've been writing has been working so within our computer's Choice let's console.log whatever that is so if this does work after clickingone of these buttons the computer is either going to pick rock paper or scissors the computer picked scissors just now scissors scissors it really like scissors apparently so yeah the Player's Choice is being populated with the string ofrock paper or scissors I just wanted to confirm that and we need a result what are we going to display to the screen result will be an empty string for now first let's check to see if the Player's
Choice is equal to the computer's choice that means it's a tie if Player's Choice is strictly equal to the computer's Choice maybe we both pick rock well well then we'll take our result to be displayed and set itequal to be it's a tie else somebody is going to win let's add an else statement we can use a switch we can examine a value against matching cases we'll examine the Player's Choice does the Player's Choice matchthe case of rock do these two Val use match if so we'll use the tary operator we'll check the condition of if our computer's choice is strictly equal to scissors if so question mark That's the tary operator ifwe pick Rock and the computer picks scissors we will return U win otherwise if this condition is false well that means the computer picked paper if our choices already don't match and we picked rock that means they either
picked scissors or paper if they didn't pick scissors that means they picked paper so they win that means we lose you lose whatever string is returned we're going to assign it to result result equals whatever is returned eitheryou win or you lose then we should add a break after this caseall right let's copy this case and everything within it let's paste it if the Player's Choice matches the case of paper and the computer's choice is strictly equal to rock that means if that's true you win else youlose let's copy this case and everything within
it case scissors if the computer's Choice equals paper then you win otherwise you lose after we move beyond the IFL statements we need to update the text on the screen so we will take the players
display set the text content to equal a template string of player col in space add a placeholder the Player's Choice did we pick rock paper or scissors then let's do this with the computer's Choice select the text contentof the computer display the text will be computer we will display the variable of computer Choice the one that was picked randomly and take our result display which has no text content currently set it equal to be resultokay let's see what we have currently let's pick Rock it's a tie paper you win scissors you lose what we'll work on next depending on the result that's displayed if we win I would like the text to begreen if we lose I want the text to be red going to our CSS stylesheet we're going to add three classes green text red text pick a font color pick something
green and for the red text pick a red font color if we win or lose we're going to add one of these classes to the class list of our result display so going back to to our Javascript fileafter we display the result now we're going to add a switch we're going to examine our result we will add a case of you win if our value matches this case let's take our result display access the classlist use the add method add the class of green text then break let's copy this case paste it we will add a case for you lose add the class of red text if we lose let's see what wehave currently if we win you get green text if you lose you get red text but now if it's a tie we have red text with each new game we should reset the color back to the original so
before updating the color and displaying it let's take our result display access the class list use the remove method remove any class of green text and red text let's see if this works you lose it's a tie that'sblack you lose you win the colors seem to be working all right now let's add scoring mechanism we'll have to head back to our HTML file after our result display we're going to create a div element the firstdiv El will have a class of score display the text for the score display will be player score colon space then we'll add a span element within with text of zero row I will give the span element aunique ID of player score display the reason I'm putting this number within a span element I'm going to style this number different from the rest of the div element the player score okay let's copy this div element and
paste it we need another for computer computer score the ID of the span element will be computer score display going back to our c a stylesheet we'll add the following after our result display we will select the classof score display increase the font size font size will be 2 R for the actual numbers I'm going to change the color with the CSS property where the font color is green I'll add an additional selector let's selectthe ID of player score display I would also like that to be that shade of green and for the red text let's select the ID of computer score display so the computer score that number will be red okaynow we just need to add functionality to the scoring mechanism so back to the top we're going to select the ID of player score display const player score display equals doc min.
getet element by ID player score display and we need the same thing for the
display and we need a score value a number so we can work with it let player score equals zero let computer score equals z going to the bottom of this function within our switch within our case of youwin we're going to increment our player score player score Plus+ then take our player score display and update it access the text content set it equal to whatever the player score is then let's do this with our computercomputer score Plus+ that's if we lose and computer score display equals the computer score and that should be everything let's see if this program works you lose you win you win it's a tie you win you win youlose the player score is four the computer score is two all right everybody so that is a game of rock paper scissors you can make using
JavaScript hey what's going on everybody so in today's video I'm going to show you how we can create an image slider program using JavaScript you will need some images to work with I would recommend finding three or moresomewhat related images to whatever you would like to create an image slider for once you find your images put them within your website folder and we are ready to begin okay let's do this thing everybody so we willcreate a development to contain everything this development will have a class of slider within this development we will create another development this development will have a class of slides to contain our images within this inner div element wewill create three image elements the first image will have a class of slide with this image element I will set the source attribute to be a relative or absolute file path let's begin with image one whatever you currently
have I'll copy the name of this image including the extension so my image has a name of image 1.jpg and for some reason if this image can't display I'll add some alternative text with the alt attribute let's sayimage number one and there is my image I will copy this image element paste it twice or once for every image that you have then I have image two and image three let me change those we have imagetwo and image three so you should have three or more images depending on what pictures you're using and how many then we're going to add some Arrow buttons for the time being that will be down at the bottomso we will create a button element now you could use a left angle bracket let me zoom in but I think there's a better option there's a unic code character for a left pointing angle bracket which looks like
this we will use the Unicode character of Ampersand # 100094 I think that looks better but you do you all right then let's create a right angle bracket with another button the number is 1 95 so that willcreate a button with an arrow that points to the right for the previous button the left one I will assign a class of prev meaning previous and the next button will have a class of next when we clickon these buttons we'll call a JavaScript function we need to set the onclick vent Handler equal to a JavaScript function for the previous button we'll call a function of prev slide meaning previous and for the next button wewill call a function of next slide to go to the next slide okay and that is all the HTML that we need for now let's go to our CSS stylesheet we will select our class of slider that contains
everything class slider we're going to use relative positioning these elements will move relative to their normal position using relative so we have position relative I will set a width of 100% as well as margin Auto to to Centereverything horizontally now just in case if our images are really big I will set the Overflow property to be hidden so take our class of slider select all the images with these images I will set their width tobe 100% and for now I will set the display property to be none we don't want to display all the images right away so they should disappear let's add a little bit of functionality before continuing let's go toour Javascript file I'm going to create a node list of all the images within our class of slides so I will create a constant of slides which will be a node list equals document.
query selector all we will select all elements within the class of slides that are images image elements we will also declare an index of the current slide let slide index so this will be zero initially to start atthe first slide we'll be using the set interval function set interval will return an ID that we can work with so we will declare a variable to hold to that let interval ID for now I'll set it tobe null meaning no value okay let's declare our functions we will have a function to initialize our slider this will populate our web browser with the first image when we call this function then we need a function forshow Slide there will be one parameter an index an index of the next slide we would like to go to a function for the previous slide prev slide and a function for next slide function next slide within our
function of initialized slider we will take our node list of slides at index of our current slide index which will be zero initially I will access the class list and add a class of display slide which we stillneed to work with and then we will call this function right away okay we need to build this class still display slide we will select all image elements that have a class within their class list of display slideif an image has this class we will set their display property to display as a block we should get our first image if you would like although it's not necessary we could display this image after all of theDom content loads by using an event listener here's how if you would prefer to wait for all the Dom content to load we can take our document add an event listener we will wait for the event of Dom
content loaded once all of the Dom content loads pass in a call back to initialize slider so this would work too and I would say it's the preferred way rather than just calling this function initially wait for allthe Dom content to load then display our first image by calling this function within the initialized slider function we will use the set interval function we will call the next slide function after a given amount of seconds let'ssay after 5 seconds I would like to go to the next slide and display the next image whatever is next within our node list in order for us to work with this interval this function is going to returnan interval ID so we can clear it later if we need to we will take our interval ID set it equal to the set interval function so I am going to console.log my interval ID just to see what
it is so let's save and run everything go to console so this interval has an ID of one if I need to clear this set interval function I can access it by its ID which is currently one andwe can get rid of this line to avoid displaying an image if we don't have one we can wrap these two lines of code within an if statement we will check if our node list of slides its lengthproperty is greater than zero if we do have slides then display it and use the set interval function if there's no slides no images then don't do this okay then we're going to go to the next slide functionwe're going to increment slide index by one slide index Plus+ and then we will will call the show slide function pass in our slide index after incrementing it and that is all we need for next slide then we
have the show slide function within our show slide function we will access our node list of slides use the for each method to iterate through all of them I would like to take each slide Arrow do this takeeach slide access its class list then remove a class from the class list we will remove the class of display slide if it's time to move to the next slide we don't want to display the current slide anymorewe'll remove display slide so that it's no longer displaying as a block remove these properties then outside of this for each method we will add display slide to the next slide then we will take our slides at indexof slide index access the class list of the next slide then we will add a new class add the class of display slide so that it displays as a block and let's see if this works after 5 Seconds
we should move to the next slide and that does in fact work let's wait again for the next slide and that has worked too we need to reset our slide index because right now we're going out of boundswe only have three slides in this example within our show slide function We'll add an if statement and an lse if
statement if we reach the end of our slides we need to reset the slide index and set it back to be zero if our index that's passed in is greater than or equal to our node list of slideslength property if we reach the end we need to take our slide index and reset it to be zero now if we go backwards with the previous button if our index is less than zero we will take theslide index set it equal to our slides length property minus one to set it to the end if we're on the first slide and we hit the previous button that will bring us to the last slide these imagesshould Loop let's see see if that does
work so we're on our green car and we should go to our blue car next and that does work our initialized slider function is done if we click on the next button we should be able to go tothe next slide right
away now we have to work on the previous button and add some functionality to that within the previous slide function we will take our slide index and decrement it with minus minus then call the show slide function passin the current index now we should be able to move forward and back now if we hit the previous button CU we want to look at an image the timer is still going we'll still go to the nextslide if we would like to take some time to admire one of these images we can clear the set interval function by using its interval ID so if somebody were to hit the previous button let's clear the timerwe will use the clear interval function we will pass in that interval ID our set interval function is still going to move the slides forward but if I were to hit the previous button that interval is going to
stop we are done with all of our JavaScript functionality we're going to apply some CSS styling to the buttons and even add a transition animation to the next image we will style our buttons next within our class ofslider select all buttons I will set the position property to be absolute positions an element relative to its parent meaning the slider element with absolute positioning I will set the top property to be 50% these buttons will thenbe positioned on the Y AIS at 50% meaning the middle then I will use the transform property I will translate them on the Y AIS by minus %.Translate Y is a function we're moving these buttons up by 50% of the element's height that will put this button right in the middle take 50% of the height of the button Move It Up by that amount I'llincrease the font size font size 25 pixels or better yet let's do like 2 RM okay now for the background color I'll set it to be black but I'm going to lower the alpha on it so it's transparent
I'll set the alpha to be 50% and for the font color color I'll set that to be white okay you can see our two buttons are overlapping currently I'm going to remove the border around the buttons order noneand change our cursor to be a a pointer if we hover over one of the buttons so these buttons each have a class previous and next let's select the previous class I will set the left property to bezero to left align it and with the next class that's the next button I will set the right property to be zero to align it to the right I'm also going to add a little bit of padding tooaround the buttons let's add some padding here padding 10 pixels by 15 pixels that looks pretty good we are going to add an animation at Key frames we need an animation name we will name this animation fade for
a fade effect from this property of opacity I can't spell today 0.5 meaning 50% two this property opacity one for 100% when a new image is displayed the opacity is going to be 50% so it's transparent then afterthe animation is complete set it to be one for 100% now we just have to utilize this animation of fade all images that have the display slide class we will set their animation name when that image is displayedto be fade how long do we want this animation to take we will set the animation duration to be about 1.5 seconds okay let's see if this works we should get a fade animation when each new slide appearswe can move forward and we can move back all right everybody so that is an image slider that you can create using JavaScript HTML and
CSS hey everybody in today's video I got to introduce to you the wonderful world of callback hell callback hell is a situation in JavaScript where callbacks are nested within other callbacks to the degree where the code is difficultto read if you Nest too many callbacks within other callbacks your code starts to form a pyramid and it's really difficult to work with callback hell is an old pattern to handle asynchronous functions in Java Script nowadays wehave promises as well as a sync and a wait to avoid callback hell which we'll discuss pretty soon to help us avoid callback hell we should be familiar with what it is I'm going to create four tasks thesewill be functions function task one these will be synchronous functions we don't need to use callbacks for synchronous functions then we'll change these to be asyrus functions within task one we will console.log task one complete okay let's copy
task one paste it three times for a total of four tasks we'll have task two task three and task four in order from the top down we will execute task one followed by task two task three and taskfour when all four tasks are complete we will console.log all tasks complete these functions work synchronously they're all in order task one is complete then two 3 then four then we get the final message of all tasks completebut what if these were asynchronous functions they're not going to follow this order from the top down so to make these functions asynchronous one thing we could do we can enclose this code within the set timeout function settimeout set timeout takes two arguments a call back and a time in milliseconds in which to complete this code for the call back this could be a call back an anonymous function or an arrow function I'll write an
arrow function parameters Arrow do this say the task is complete after 2,000 milliseconds let's do this with the other taskstoo so task two will be complete after 1 second 1,000 milliseconds task three will be complete after 3,000 milliseconds now task 4 task 4 will be complete after 1,500 milliseconds okay let's try this again I need these tasksto be completed in order starting from one all the way to four it says that the tasks are already complete then the tasks are completed in this order task 2 task 4 Task 1 and task three so that'sthe problem with asynchronous code asynchronous functions can complete at any time the rest of our program doesn't wait around for them to finish if I absolutely need these tasks to complete an order starting with 1 then 2 34 each of these functions can accept a call back so we need to set up that parameter after we say that that task is complete we will execute the call back to the next function so let's do this
if we need these tasks to complete an order starting with one we would take one and there's one parameter a call back we'll pass in a call back to task two we can pass in a call back andAnonymous function or an arrow function I like Arrow functions though parameters Arrow do this what are we going to do when task one is complete we'll call task two task two also accepts a call back again this canbe a call back an anonymous function or an arrow function this will be an arrow function parameters Arrow do this what do we want to do when task two is complete call task three task three also accepts acall back we'll use an arrow function parameters Arrow do this now when task three is complete guess what we're going to do call task four task four task 4 accepts a call back we'll do this parameters Arrow then
would like to console.log all tasks complete all tasks complete this should work now task one complete task two complete task three complete task 4 complete all tasks complete so what we've done is use callback hell it's where you'renesting callbacks inside of other callbacks if you have a lot of tasks to complete an order it can become very unman manageable hey this is bro from the future one thing that I wanted to mention is that fourlevels of callbacks isn't too unreasonable but when you add additional levels on top of that that's when you're starting to approach the levels of callback hell where the code can become unmanageable and really difficult to read what I'vewritten in this video isn't too unreasonable but hopefully you can see how we've come to start that pyramid pattern that is all all right everybody so that is callback hell it's a situation in JavaScript where callbacks are nested
with other callback where the code is difficult to read it's an old pattern to handle asynchronous functions in some upcoming videos we'll be discussing promises as well as a sync and a wait to avoid callback hell and welleverybody that is callback hell and why you should avoid it in
JavaScript what's going on everybody so in today's video I got to talk about promises in JavaScript A promise is an object an object that manages asynchronous operations such as querying a database space fetching a file Gathering resources thoseyou could consider asynchronous operations they can take an indeterminate amount of time you can wrap a promise object around some asynchronous code the promise object promises to return a value that promise object will be pending then either thatpromise will be resolved if the task completed successfully or rejected if it failed for some reason maybe the promise couldn't fetch that file resolved if it did A promise is an object will create a new promise object withnew prom then pass into a function usually you see this is an arrow function there's two parameters resolve and reject Arrow then do some asynchronous code so in this demonstration we're going to be doing some chores if you
live with your parents maybe your mom asked you to do these chores or with the roommate these are the tasks you need to do or your significant other wants you to do these tasks anyways we have some choresto do we have to walk the dog clean the kitchen and take out the trash I'll create functions for each of these chores first we'll start by using callbacks then I'll demonstrate the use of promises and how they'rehelpful so let's create a function to walk dog to make this asynchronous I'm going to add a set timeout function this takes a call back and an amount of time in milliseconds to complete this code let's say walkingthe dog takes 1,500 milliseconds what code would we'd like to perform let's write an arrow function to keep it simple parameters Arrow do this let's console.log after completing this chore you walk the
dog okay that'll be the first function let's create a function to clean the kitchen function clean kitchen this will take a long time 2,500 milliseconds let's say when we complete this task we will print you clean the kitchen
and a third function take outtrash you take out the
trash taking out the trash it's really quick it takes half a second 500 milliseconds if I need to do these chores in order I would need to use some callbacks after walking the dog we will call a callback to clean kitchen after we clean the kitchen we will take out the trash we need to modify these functions so that they accept some call backs after our code is complete we will invoke the call back callthe Callback so let's add that parameter to each of these
functions now if we want to call all these functions in order we would have to start using call back hell which we learned about out in the last video so first I would like to walk the dog Iwill call that function pass and a call back but we'll use an arrow function then we will clean the kitchen pass in a call back I'll use an arrow function take out trash and we'll pass in a callback to do this when we complete all the chores console.log you finished all the chores okay let's see if this works you walk the dog you clean the kitchen you take out the trash you finished all the choresif we have a lot of callbacks to work with we'll end up going to call back hell you don't want to go to call back hell so what we'll use instead are promises with all of this asynchronous code
we'll wrap it within a promise by using a promise we don't need callbacks instead of using callbacks we'll use method chaining we'll method chain our Pro promises here's how how we'll modify these functions is that at the endof each function we will return an object return a new promise return a new promise object and follow this formula we have two parameters resolve and reject resolve reject Arrow do this asynchronous code within an arrow function takeall of the asynchronous code cut it place it within the promise our promise promises to return a value it's either going to be resolved or rejected we're going to modify this function we don't need to work with callbacks anymore we can get rid of those get rid of the parameter and the portion of the code where we call the call back if we would like to display a message when the promise resolves when it finishes
successfully we will instead call the resolve parameter it's a function this message is the value the argument that we're passing in after you finish walking the dog here's your completion message when the promise resolves let's modify the restof the functions so that they use promises we will return a new promise two parameters resolve reject Arrow do this asynchronous code let's cut our current asynchronous code paste it remove the call back parameter we don't need itanymore and we don't need to call the call back when this promise resolves pass along this message you clean the kitchen let's do this with take out trash we will return a new promise two parameters resolve reject Arrowdo this cut the asynchronous code paste it within the promise remove the call back and where we call the call back when we resolve this promise pass along this message we no longer need to use callback hell instead
we're going to use method chaining first we're going to walk the dog clean the kitchen and then take out the trash in that order we will call the walk dog function and then we're going to Method chain followthis with the then method walk the dog then what is what we're saying the walk dog function does provide a value parameter this message we can use that message for something that's going to be stored within value that'sgoing to be the parameter that's provided to us take the value let's print it console.log my value so when I run this program we should only be walking the dog you walk the dog and nothing else looks likeI misspelled resolve as resolves there after walking the dog I would like to clean the kitchen so I need to call that function next within our Arrow function we'll write more than one statement we need to enclose this
within a set of curly braces print our value and then do this function return clean kitchen and then call it we'll add another then method then take the value provided by clean kitchen that will be this one takethat value arrow console.log that value
you walk the dog you clean the kitchen then we'll take out the trash at the end we'll add another statement to this then method we will return take out trash invoke this method then we will take the valueprovided to us when it resolves this value do this code console.log that
value you walk the dog you clean the kitchen you take out the trash so after taking out the trash that's our last chore let's add another line of code after displaying you take out the trash let's console.log youfinish all thechores you walk the dog you clean the kitchen you take out the trash you finished all the chores by Method chaining then methods it's a lot easier to write than nesting call backs now sometimes with asynchronous functions dependingon the task the task May Fail let's say we're trying to locate a resource a file if we can't locate that file and we're using promises we don't want to resolve that promise because we couldn't locate that fileinstead we want to reject that's what happens when an asynchronous function fails to do something when inside a promise so let's change our functions around within set timeout let's create a variable const dog walked did we accomplish this
this will be true or false we'll use an if statement if dog walked then we will resolve it if we walked the dog else we will reject we'll pass in a different value you didn't walk the dog okaylet's do this with the other functions let's create a constant of kitchen cleaned equals true if our kitchen is cleaned if that is true we will resolve this promise you clean the kitchen else let's reject pass along thismessage you didn't clean the kitchen and lastly take outtrash const trash taken out let's set that to be true if the trash is taken out resolve the
reject you didn't take out the trash if a promise might reject there's one more method we need to add to the end of this chain we need to add a catch method to catch any errors this will catchany Rejects this is similar to error handling we'll be provided with one value an error Arrow do this let's console.log or even console.error the message provided to us with reject that's what the error is going to be we'll successfully walk the dog that will be true and cleaning the kitchen will be true but taking the trash out will be falsewe weren't able to complete this chore these are the results you walk the dog you clean the kitchen you didn't take out the trash how dare you we'll keep on completing these tasks until we fail at one ofthem so if walking the dog was false that was our first
task this first promise was rejected we don't even attempt to resolve these other promises all right everybody so those are promises they're an object that manages asynchronous operations you can wrap a promise object around some asynchronous code thesepromise objects promise to return a value they will be pending until they complete then they'll either be resolved if that task completed successfully or rejected if it failed for some reason and well everybody those are promises in JavaScripthey everybody so today I got to talk about a sync and a weight in JavaScript a sync and a waight are two keywords by using these two keywords together they allow you to write asynchronous code in a synchronousmanner a sync makes a function return a promise a wait makes an async function wait for a promise we'll discuss async first in this sample program from the last topic we have some chores to do we have to
walk the dog clean the kitchen and take out the trash each of these functions returns a promise a promise that can either resolve or reject based on the code that's written if the dog is walked if if that'strue resolve if it's false reject a function can be declared with a sync a function declared with a sync will return a promise however that promise that's returned doesn't resolve or reject in a way you could say it'san empty promise if I were to run this code this is what happens uncaught reference error resolve is not defined if an asynchronous function returns a promise that either needs to resolve or reject adding a sync to itreally doesn't benefit us a sync works together with a weight by using these two keywords together when calling all of these asynchronous functions in order we don't need to Method chain then statements there's a more synchronous manner in
which we can write the same code but we'll need to contain it all within an async function async function we'll create a function to do chores then we will need to call this function somewhere let's do so righthere first we need to walk the dog walk the dog returns a promise that's where the await keyword comes in a wait makes an async function wait for a promise before continuing we're going to create a constant ofwalk dog result equals use the await keyword await walk dog then we will console.log the walk dog result you walk the dog now let's do this with clean kitchen we're going to be writing this code in a synchronousmanner line by line linearly we will create a constant for clean kitchen result equals await the next promise await clean kitchen then console.log clean kitchen result let me close this you walk the dog you clean the kitchen and
last we have take out trash const takeout trash result equals a wait take out the trash then console.log the result you walk the dog you clean the kitchen you take out the trash let's add one more line whenwe finish everything one more line of code you you finished all the chores you walk the dog you clean the kitchen you take out the trash you finished all the chores let me show you what happens if weattempt to use a weight within a function not declared with a sync uncaught syntax error a weight is only valid in async functions that's why a weight depends on async a weight makes an async function wait for apromise before continuing now if your promises can reject let's say that dog walked is
false uncaught in promise you didn't walk the dog we'll surround all of this code within a tri block then catch any
errors catch one parameter of error we can console.log or console .error the error you didn't walk the dog all right everybody so that is a sync and a wait a sync makes a function return a promise a wait makes an async function wait for a promise by using thesetwo keywords together we can write asynchronous code in a synchronous Manner and well everybody that is a sync and a wait in JavaScript what's up everybody so today I got to talk about Json files using JavaScript Json meansJavaScript object notation it's a data interchange format most of the time it's used for exchanging data between a server and a web application they can have a few different formats usually you'll see a Json file as an objectan object made up of key value pairs or you may see them as an array an array of values or some combination of both you can have an object where one of the values is an array and or
you could have an array of objects like this just to understand the format we'll create a new Json file let's go to our website folder create a new file we'll create an array of names the file extension isJson we'll Begin by writing an array with a set of straight brackets let's add a few names just some first names SpongeBob Patrick Squidward
Sandy this is a valid Json format let's create a new Json file just for a single person this will be an object new file person.Json this time we will create a single object this object will have key value pairs we will have a name key and a value of SpongeBob each key value pair is going to be comma separated SpongeBob will havean age key of 30 and a Boolean of is employed is SpongeBob currently employed that will be true this is also a valid format our Json file contains one object an object made up of key value pairs objectscan even have arrays as one of their values we will create an array of hobbies what what does SpongeBob like to do this will be an array
jellyfishing karate and cooking let's create one more Json file we will create a Json file for people this will be an array of objects people.Json we're going to create an array of objects within this array we'll create one object what key value pairs should this object have we'll just reuse what we have for SpongeBob excluding the array to keep it simple okaythat will be the first object let's create another object we need another set of curly braces the second object will have a name property of Patrick age 34 is employed will be false the next object this will befor Squidward age 50 is a employed true he works at the Crusty Crab one last object name Sandy age 27 is employed false Sandy is self-employed all right we have an array of objects each object can have itsown unique key value pairs so let's close out of these Json files but we'll hold on to them so Json formats they're one long string to represent that object or array using the stringify method of Json we can
convert a JavaScript object or an array into a Json string so let's copy what we have for names I will create a constant of names equals that array we'll convert it to a Json string const Json string equalsaccess Json Json is a built-in object that's provided to us to work with Json files we will use the stringify method then pass in our array or our object currently if I were to console.log my names before stringifyingit here's the result we have an array of strings to work with after using the stringify method on names we'll be given one long string to represent this array if I was to use this on an object let'scopy what we have for personI will create a const of person this will be an object I'll just paste what I have for SpongeBob first let's console.log person here's my person object then let's stringify it and display the Json string Json files work
with one long string that represents an object or an array let's stringify our people it's an array of objects
const people equals paste what we have let me show you what happens when I console.log people before stringifying it we have an array of objects each object has its own key value pairs then if I was to stringifyit here's the result one extremely long string now we'll use parse parse converts a Json string to a JavaScript object so let me reformat
these to convert these objects or arrays into a string we can surround them with a pair of back
ticks so let's rename these let's say Json names Json person then Json
people these objects and arrays are all in a Json format to convert them to their original form we can use the parse method of Json I will create a constant of par data equals Jsonparse pass in our data of Json names and then let's console.log let me show you Json names first before parsing it we have a string representation of an array but after parsing it it becomes a JavaScript array let'sdo this with our string representation of an object Json person normally it looks like this and then after parsing it we have a JavaScript object and then Json people it's an array of objects then we'll parse it andhere's the result an array of objects now I'm going to show you how we can fetch a Json file we'll talk about fetch more in the next topic fetch is a function as an argument we can pass in
a relative or absolute file path or a URL we'll discuss that in the next topic I would like to get my Json file of let's go with person so I will list the relative file path these files areright next to each other I just need to type person.Json fetch returns a promise we will follow this with the then method then do this we'll be provided with a response object take our response Arrow do this we will take our response object convert it to a Jsonformat using the Json method then let's display what we have currently then take the value arrow console.log that value let's see what we have yep there's SpongeBob we have successfully fetched a Json file let's do this with ourarray of names we have an array of strings of first names and people people.Json we have an array of objects one object for each person if you would like to iterate through all the objects let's rename value as values we'll use the built-in for each method of arrays values.
for each take each value Arrow do this console.log each value now we're iterating through and printing each object if you would like some of the specific properties like make name follow the value with name SpongeBob Patrick Squidward Sandyor age or isemployed oh and another thing that I'm forgetting be sure to add a catch method to catch any errors just in case we can't fetch this Json file for some reason console.log or console.error the error message we'll talk about fetch more in the next topic all right everybody so those are Json files Json means JavaScript object notation it's a data interchange format it's mostly used for exchanging data between a serverand a web application Json files are usually objects or an array or some combination of both to convert a Json object to a string you can use the stringify method to convert a Json string to an object you
can use the parse method to fetch a Json file you can use the fetch function which we'll talk about next and get more in depth with and well everybody those are Json files using JavaScript well it's going oneverybody so in today's video I'm going to show you how we can fetch data from an API using JavaScript and at the end of this video we're going to create a project where we can fetch some images ofPokémon depending on what Pokemon you type in so sit back relax and enjoy the show all right people so we got to talk about fetch fetch in JavaScript is a function it's used for making HTTP requests to fetchresources including but not limited to Json styled data images files resources of that nature the fetch function simplifies asynchronous data fetching it's used for interacting with apis to retrieve and send data asynchronously over the web fetch has two
arguments a URL of the resource and an object an object of options I won't be talking about options in this video that's more advanced JavaScript one of what you may see is a method property the default is getto get a resource you can use post to send some data put to replace some data and delete to delete some data so the default is get but we don't need to explicitly state that we'll just be focusingon getting data with only a URL to fetch something we have to use the fetch function and pass in a URL what I thought we could do for this video is fetch some Pokemon data from the Pokémon APIif you want to follow along you can go to this URL I would like to fetch some data on Pikachu because everybody knows about Pikachu and here's some of the data on Pikachu this resource is one gigantic object
Pikachu has a name an ID number a type Pikachu's an electric type there's stats such as his attack power HP there's even image Sprite which we'll work with later we will copy this URL and paste it within thefetch function we will pass in a string representation of this URL the fetch function is promise-based it's either going to resolve or reject so we should add a then and a catch method to catch any errors error Arrowdo this let's console the error if there's an error once the promise resolves will be provided with an object a response object take our response object Arrow do this for the time being let's console.log our response just tosee what it is exactly so here's our response object the body contains the data we're looking for for Pikachu this response object has a status code of 200 that means it's okay here's where you may see that status
code of 404 if you can't locate a resource it has an okay property if fetching this resource was okay this is going to be true if not it's false there's also a URL here too now our next stepis to convert it to a readable format there's a few different methods there's array buffer blob text and Json these are all methods we're interested in the Json method in this example so our next step is to takeour response object convert it to Json using the Json method this is also promise based once this promise resolves let's follow this with a then method then take the data our Json data that's going to be returned tous Arrow do this let's console.log my data just to see what it is so after fetching data on Pikachu convert the response object to a Json format and here's my data for Pikachu we have a name an ID
Pikachu stats such as his HP and attack and wait and many more things with this Json data you can access one of the properties I would like just Pikachu's name data.name Pikachu data dot weight how much does Pikachu way 60 60 units of something whatever unit of measurement they use in Anto what is Pikachu's ID 25 near the end of this video we're going to fetch the Spritesof the Pokémon now for some reason if we try and access a Pokemon that doesn't exist as of the filming of this video SpongeBob is still not aPokemon we get a status code of 404 meaning we could not find this resource SpongeBob is not a Pokemon unfortunately so even if we can't locate a resource our promise is still going to resolve it's not going toreject we need to check to see if our response is not okay let me demonstrate I will console.log my response object here's my response object it is not okay your response will be okay if the status is within
the 200 range since we have a status of 404 we couldn't locate this resource okay is false we're going to throw an error if our property of okay is false within our first then method we'll write a fewstatements we need a set of angle brackets before continuing let's check to see if our response access the okay property then use the not logical operator if our response is not okay if it's false we're going to throwa new error and then catch it using the catch method we can write a custom message let's say something like could not fetch resource if our resource is okay we won't execute this code otherwise we will return ourresponse object in a Json format let's try and retrieve Pokemon data on SpongeBob okay we have an error but we have caught this error using the catch method error could not fetch resource then let's get data on Pikachu
again and there Pikachu and his ID
number if you would prefer to use a sync and a weight here's how let's delete all this we will create an async function so that we can use a weight within it I will declare a function to fetchdata no parameters do all this we will create a try and catch block try and catch catch has one parameter an error if we receive an error let's console.error the error within our Tri block we will create a constant of response the fetch function is going to return an object a response object we will await our promise that's returned by fetch then we need to getthat URL again let's get data on a different Pokémon another Pokemon that I like is tyion honestly I think tyion is my favorite Pokemon all right here's the stats for tyion I'm going to copy this URL pass it
to the fetch function as a string once the promise for fetch resolves we have to see if the response is okay we'll use an if statement if our response object is the okay property not okay if our responseis not okay if we can't locate this resource then we will throw a new error let's say could not fetch resource if our response is okay we will create a constant for our data equals await take our responseand convert it to Json this also returns a promise that's why we're using a wait then we will console.log our data and then we have to call the fetch data function because I forgot to do that call fetchdata and here's the stats for tyion Name tyion ID 157 tyion is a fire type that's how to use a sync and a weight to fetch a resource now that we know what we're doing we're going to create
a text box and a button to search a Pokemon and pull up a Sprite of that Pokemon and display it so going to our HTML file we will create an input element with the type attribute of text becauseit's a text box I will set the ID of this input element to be Pokemon name it's a little small right now we haven't applied any CSS I will add a placeholder of enter Pokemon name then we needa button I will create a button element with text of fetch Pokemon I will set the onclick event handler equal to a JavaScript function let's call that function a fetch data
then I will add a break after fetching some Pokemon data we have an image to work with I will set the source currently to be an empty string I will display some alternative text if we can't display theimage of Pokemon Sprite and I will give this element an ID of Pokemon Sprite to not display the image currently we can access the style access the display property and set it to be none then if we dowant to display it we can set display to be a block let's go to our Javascript file within our Tri block we will create a constant of Pokemon name equals document.getet element by ID the ID that I'm selecting is Pokemon name access the value of this input element now if somebody types an uppercase characters I'll take the value make all the letters lowercase I will method chain the
two lowercase method two lowercase
method with our fetch function we're going to use a template string with a pair of back ticks for the Pokémon's name we will use a placeholder and pass in our Pokemon name variable so now when I type ina Pokemon's name like Bulbasaur we should get data on that Pokemon if it exists so let's go to inspect console and here's data on Bulbasaur Bulbasaur's ID is one Bulbasaur is a grass type and I think he's apoison type too if I'm not mistaken this Json data also has Sprites images of each Pokemon we're going to fetch the front default so we don't need console.log anymore we'll create a constant of Pokemon Sprite to get thatimage equals take our data access the Sprites property get the front defaultSprite then we will get our image element this one that has an ID of Pokemon Sprite const image element equals document.
getet element by ID the ID that I'm getting is Pokemon Sprite we will change the CSS of this element take our image element access its source attribute right now it's currently empty our source is an empty string setthe source equal to our Pokemon Sprite this is a constant then we will take our image element access the style attribute access the display property and set it equal to be a block because right now it's none nowwhen I type in a Pokémon's name like Charizard and fetch that Pokémon we get the image of that Pokémon it is a little small however it is a Sprite Sprites tend to be very small or we can getmeww or whatever other Pokemon you can think of I think there's like over a thousand Now where's tyion there's tyion all right everybody so that is how to fetch data from an API you got to use the fetch
function it's is used for making HTTP requests to fetch resources you can fetch Json style data images files the fetch function simplifies asynchronous data fetching it's used for interacting with apis to retrieve and send data asynchronously over theweb and well everybody that is how to fetch data from an API using JavaScript hey everybody so in today's video we're going to create a weather app that fetches data from an API you can look up any didn'tget the weather if that sounds good to you then sit back relax and enjoy the show if you would like to follow along you will need your own API key the API that we'll be using is openweathermap.org youdo need to sign up for an account though it is free to sign up for an account you can go to sign in if you're currently not registered you can create an account for free once you're signed in
you'll need an API key go to my API Keys it may take you some time to get an API key generated for you mine took about 15 minutes and once you get it make sure it's active we willneed that API key about 20 minutes into this topic hopefully for you by then it'll be generated okay let's do this everybody we will Begin by creating a form element the form element will have a class of weatherform our form element is going to have an input element and a button within this input element we'll type in the name of the city we would like to retrieve the weather data 4 so the type of thisinput element is going to be text for some text the class will be City input so a user can type in the city and we'll add a placeholder let me zoom in a little so you can see it
the placeholder will equal enter City then we'll need a button let's create a button element with text of get weather the type of this button will be submit it's the submit button for our form after retrieving the weatherdata we'll display the weather data in a card format like a Pokemon or Yu-Gi-Oh card so we will create a div elopement with a class of card but before applying some CSS we should at least add some placeholderelements so we can style them and see the changes for the time being let's create an H1 element we will be deleting these elements later so don't get too attached I will set the class of this element tobe City display We'll add a sample City let's say Miami or pick a city if you're choosing then I will create a paragraph element the class will be temp display meaning temperature let's say the temperature is 90° fah
or pick something in celsius if you're on Windows to add a degree symbol you can hold alt then type 0176 Miami is going to be 90° F then we'll create a paragraph element for the humidity class equals humiditydisplay for the text let's say humidity colon space then a percentage 75% then we need a description of the weather this will be another paragraph element the class will equal description display desk meaning description for the description let'ssay clear skies I'll also display an emoji depending on what the weather is the class will be weatherEmoji I'll use a sun for some reason if we can't display the weather data such as if we can't locate a city let's add the following paragraph the class of this element will be error display We'll add thetext of please enter a city that is all the HTML that we need for now we're going to apply some CSS styling next so now let's head to our CSS stylesheet we are going to select the body of
document select a font family I will pick Ariel with a backup of s serif I'll change the background color of the body background color pick a color I'm going to use hsl values I will set the lightness tobe 95% so it's a light gray color I will set all margin around the body to be zero then I'll use flexbox to display the element elements display Flex the flex direction will be a column to arrange allthe elements in a column then align item Center to horizontally align all the elements align item center now we'll select the class of weather form that'll be this form that has an input element and a button all we'lldo is add a little bit of margin around the entire form 20 pixels then we'll select our city input that's going to be the text box class of City input I will add some padding of 10 pixels let
me zoom out to 100% increase the font size to 2 RM set the font weight to be bold I'll add a border two pixel solid and pick a
color but all lower the alpha so it's transparent to 30% there's our border currently border radius around the corners let's do 10 pixels add some margin of 10 pixels that'll separate this element from the button and set awidth of 300 pixels okay let's style the button next okay we are going to select all buttons that have an attribute where the type equalssubmit so that's going to be for our submit button that says get weather let me scroll down okay I'm going to add some padding around the button 10 pixels by 20 pixels I'll set the font weight to bebold I'll increase the font size to be to R pick a background color for the button I'll pick something
values I've already pre-picked a color let's go with 122 the 39% and 50% that's a good shade of green I will set the color to be white for the font color remove the border bordernone and Border radius 5 pixels to round the corners then when we hover our cursor over the button I would like it to be a pointer and that does work when we hover a cursor over the button we'lluse the hover Pudo class to change the background color so let's take our button for the type attribute is submit access the hover sudo class take our background color make it a little bit darker I'll bring down thelightness by 10% so it's at 40% so that does in fact work okay then we're going to select our card class that contains all the weather data so we will select the class of card for the background we're
going to do something a little bit different we're going to use a linear gradient instead of selecting the background color we will select the background I will use the linear gradient function there's three arguments think of a lineargradient as a slow transition between two colors we need an angle in degrees we'll say 180° for now then a color let's pick something blue and orange I'm going to pick some colors that look a little bit betterso for blue let's set the Hue to be 210 100% for the saturation and the lightness will be 75% that's a good shade of blue and for orange we'll use another hslvalue for the Hue I'll say 40% the saturation will be 100% And The lightness will be 75% so I'm hoping with this linear gradient the background color looks kind of like a sunrise or a sunset once we have
our background I will add some padding of 50 pixels I'll add a box Shadow to this card we'll add a vertical and horizontal offset of two pixels each and a blur effect where the radius is 5 pixels thenwe'll pick a colorI'm just going to lower the alpha to 50% not bad this gives our card a 3D pop effect I will set a minimum width of this card to be 300 pixels then we have to align everything within itI'll use flex box because I like Flex box display Flex Flex direction will be a column
and align items Center to horizontally align the items there we go then we'll select all H1 elements that's going to be our city name select all H1 elements increase the font size to be 3.5 RM I'll remove anymargin from the top margin top will be zero and add margin to the bottom of 25 pixels then we'll select all paragraphs that's going to be everything underneath our city select all paragraphs increase the font size to 1.5RM there's a lot of natural margin between the paragraphs let's set all margin to be zero to see what it looks like okay let's add a little bit of margin five pixels on the top and bottom zero marginon the sides that's a lot better we'll select the city display and the temperature display we're going to be selecting two classes City display comma our temp display take these two classes apply the following properties you know what
for our font size let's set that to be 3.5 RM we can honestly remove that from H1 for the font weight I will set that to be bold for the color I'll make the color a little transparent I'llset the alpha down to 75% so that our city and our temperature they're both going to be transparent then I'll add some margin to the bottom margin bottom 25 pixels okay let's select our humidity display class humidity displayset the font weight to be bold and add some margin to the bottom of 25 pixels then we'll select our description display which we shortened to desk display for the font style I will set it to be italicand the font weight will be bold I'll increase the font size to 2 RM then we'll select our weather Emoji so class weather Emoji remove all margin around the Emoji margin zero then we'll increase the font size of
the Emoji the size will be 7.5 RM so it's kind of big then if for some reason we display an error we'll display this text so this class is error display I'll set the font size to be 2.5RM the font weight will be bold I'll set the color to be something transparent I'll lower the alpha to75% okay that is all the CSS that we need let's go back to our HTML file we can delete everything within the card class we just wanted to see what it would look like with the elements populated withour card element I will set the style attribute to be take the display property set it to be none we don't want to display the card at all until we get the weather data until it's returned to usour HTML is done our CSS is done then we're ready to add some JavaScript functionality we'll declare our constants that we need const weather form equals document dot now since we're not working with IDs we can't get element
by ID we're working with classes we can use Query selector or query selector all so I'm going to use Query selector this will return the first element in this class we only have one element with this class classweather form we'll store a reference to it const City in input equals document.query selector we are selecting the class of City input that's going to be this text box const card our card is what contains all the weather data document.query selector select the class of card and give me the first element now we'll need that API key const API key equals now here's my API key please don't try and use this one specifically I will be deactivatingit at the end of this video hopefully by now you should have that API key given to you first we'll take our weather form We'll add an event
listener this is our form the text element and the submit button when we click on this button the event type is going to be submit after we attempt to submit this form we'll do the following code we'll haveone parameter an event that's going to be provided to us Arrow do this we'll fill this in later we'll declare our functions that we need we will need an async function to get weather data there will be oneparameter a city that's going to be passed in then we'll need a function to display weather info there will be one parameter data the data will be in a Json like format we'll create a function to get weatherEmoji based on what the weather is there will be one parameter a a weather ID then we'll create a function to display to the screen any errors if there are any function display error there will be one parameter
a message a message to be displayed to the window within our event listener once we have a submit event once we click the button forms do have a default Behavior where they'll refresh the page we would like toprevent that so let's take our event use the prevent default method to prevent the default behavior for a form we don't want to refresh the page then we'll have to get the city the value within this text boxconst City equals take the city input access the value store it within this variable it should be a string we'll use an if statement if City if there's a value within here this this will be true we canuse it within an if statement if there is a city do this else we'll call the display error function else we will display an error we will pass along the message to please enter a city let's fill in
the display error function we want to be sure that it works before continuing the display error function is at the bottom will be provided with a message to display we will create a constant of error display equals documentnow we'll create an element create element we will create a paragraph then we'll need to change the text content of this element error display access the text content set it equal to be our message then we're going toadd the class of error display we would like these CSS properties take our error display element access the class list then we will add a class we will add the CSS class of error display then we will takeour card element which normally displays the weather data take our card reset the text content if there is something there we'll set it to be an empty string so normally with our card the display is set to none
we'll set the display to be a block or even Flex access our card access the style access the display and I will set the display to be Flex to display it we will take our card we will appenda child element append child we will append this par paragraph of error display to the card now if I were to not type in anything and just press get weather we get this error message please enter a cityto our card I'm just going to round the corners to make it look better border radius let's do 10 pixels that's better okay moving on if we do have a city if there's text within here we will trysome code because it might cause some errors we will catch any errors that happen we have one parameter of error if there's an error we can console.log or console.
error the error then let's call our display error function we'll pass along the error and display it now we need to get the weather data within our Tri block we will create a constant of weather data equals nowwe need to await get weather data function and pass in our city so with the weight we can only use a weight within an async function since we're within an arrow function we could declare this Arrow function asan a sync function so let's preedee our event parameter with a sync so that we can use a weight we're going to wait for this function to return the weather data once we receive our weather data we willcall the display weather info function and pass along that data the weather data okay this function is complete once you've typed everything in I'm going to close this function and we can close our display error function too now
once we want to get our weather data after we have a city now we actually need to fetch the weather data we'll have to create a URL we'll create a constant of API URL this is what we'll passto the fetch function we will use a template string be sure to use a pair of back ticks we'll need to get the following URL at this web page we need to find the API call where we canpass in a city name we can copy
this within our template string we'll paste it we'll replace the city name with the placeholder and use our city variable for the API key we'll use a placeholder pass in the API
key this is what we'll pass to the fetch function we will create a response const response equals a weight we can use a weight because we're with within an async function we will fetch our API URL once wehave a response let's check our response let's console.log our response just to see what it is okay I will type in the city of Miami get weather our data should be withinconsole.log here's our response it has a status of 200 and it's okay we need to check to see if our response is not okay what if we couldn't retrieve the data I'll make up some gibberish City let's goto inspect console we have a response status 404 the response is not okay we'll write an if statement if our response is not okay we will throw a new error and pass along the this message could not fetch
weather data else if our response is okay we will return the response and we will await our response convert it to a Json format using the Json method so at the end of this function return an object that'sin a Json like format this data is going to be returned to our event listener after we get our weather data we need to display it we'll work on the display weather info function next this one let's console.logthe data we
receive I will type in Miami so it looks like that worked we have a name of Miami for the city we have the weather which is an array it's an an array of objects we have coordinates clouds prettymuch anything you can think of regarding the weather let's get the name within main there is temperature the temperature will be in kelvin we need to convert it I'll get the humidity within weather it's an array of objectswe will get the description overcast clouds and this ID eventually we'll use the ID to return an emoji there's different weather codes I'll explain that later so we're going to use some object destructuring const use object destructuring witha set AC krly brackets we will access the name property and create a variable of city city will be Miami in this case then we will access main main is a property that contains an array take main use
object destructuring again now we're within a nested object I would like the temp and the humidity then let's select our weather so whether it's an array of objects we'll have to use array destructuring followed by object destructuring giveme the
description and the ID we have to set this all equal to data to use destructuring and let me organize this to make it look nice our data is one gigantic object that has nested objects and nested arrays soafter destructuring we'll have these variables the city the temperature the humidity a description of the weather and an ID for the weather code now we can use these like variables so with our card currently we're not displaying itnow I would like to to display it we are going to take our card set the text content to be an empty string if there's already some text here we would like to reset it such as if therewas an error message take our card access its style set the display property to be Flex for Flex box just to be sure that this is working I'm going to get the weather without entering a city after we
do type in a city it should reset that's good that's what we wanted or if we make up some gibberish we have that error could not fetch weather data but then if we type in something legitimate and getthe weather it'll reset that's what we would like okay now we have to create the elements the elements that we previously deleted from the div element we need to recreate those we will create a constant for City displayto display the city document.create element our city display was an H1 element let's copy this line of code and paste it a few times four additional times we have City display temp display for the temperature that was a paragraph element humidity displayhumidity display that was also a paragraph element a description display which we shortened to desk desk display that was also a paragraph and a weather Emoji weather emoji and that was also a paragraph okay now we need to
change the text content of each of these elements but they're empty so to say let's take the text content of our city display.text content property equals our city variable that we destructured okay let's see if that works I'll type in a city get weather oh and then we need to append it take our card append child we will append thecity display element let's try that again type in Miami get the weather that should display Miami let's try Dallas Texas Dallas Oh and before displaying it we need to add the class list the CSS class for the citydisplay after adding the text content we will take our city display access its class list add the class the CSS class of City display so then when we type in a city we should have that CSS styling allright now we have to add the temperature following the same format we will take our temp display access the text content equals I'll use a template string with a pair of back ticks I'll add a placeholder pass in
our temperature add a degree symbol you can hold alt then type 0176 for a degree symbol now this is normally in kelvin actually I don't think Kelvin uses the degree symbol but we'll be changing that momentarily take ourtemperature display access its class list add the following class add the CSS class class of temp display then we have to append the element to the card element take our card we will append a child element of temperaturedisplay so now we should see the temperature but it's going to be in kelvin we have the city and the temperature for the temperature if you would like Celsius let's use deg CI you have to subtract from thetemperature 200
17315 okay but now we should probably round it so let's enclose this equation with a set of parentheses follow this with the two fixed method of numbers to round it to one decimal
place 15.6 de C if you would like a Fahrenheit temperature this is the formula take our temp in Kelvin minus 273.15 we will multiply this by 9 / 5 plus 32 so let's enclose this all within a setof
parentheses so now we should get that temperature but in Fahrenheit oh and then add F to the end 60° F then we'll get the humidity so take our humidity display element that we created access the text content setit equal to be a template string using a pair of back ticks let's add the word humidity coin space add a placeholder display our humidity variable We'll add the class list of humidity display humidity display access its classlist add the following class of humidity display then we have to append the element to the card element card.append child append our humidity display so we should get the humidity Miami 60° fhe humidity 81 let's add percent 81% yep that does work then we'll add the description a description of the weather take the element of descriptiondisplay access the text content equals the
description then add the CSS class to the class list for this element description display access the class list add the following class of description display then add the element card.append child we will append our description display let's type in Miami get the weather currently in Miami there's overcast clouds now we have to get an emoji based on the weather with our element of weather Emoji we willaccess the text content equals we will call the get weather Emoji function but we have to pass in a weather ID so we will pass in the ID variable that we receive from data once we get our weatherEmoji we'll work on that momentarily we'll take our element of weather Emoji access the class list add the following CSS class of weather Emoji then append it to the card card.append child we will append our weather Emoji all right now before we canest it we need to fill in the get weather emoi function so with this open Weather AI there are different group codes so our weather ID
is going to be either within the 200 range meaning a thunderstorm the 300 range means drizzle 500 is rain 600 is snow 700 is atmosphere such as Mist smoke or even a tornado 800 exactly is a clear skyanything greater than 800 means clouds so our weather ID is going to be one of these codes so we're going to use a switch we will examine the Boolean value of true does the value of true match oneof these cases we'll have a case for group 200 if our weather ID that we pass in is greater than or equal to 200 00 and the weather ID is less than
300 that means there's a thunderstorm we will return an emoji a thunderstorm Emojithunderstorm I don't like the look at that one that's better okay group 300 is a drizzle so let's copy this case because I don't feel like retyping it if our weather ID is greater than or equal to 300and less than 400 that means we have a drizzle we'll just add an emoji of a raining Cloud so group 500 is also rain but it's a heavier rain so let's copy this case paste it if our weatheris greater than or equal to 500 and less than 600 will return rain as well group 600 is
snow if our weather ID is greater than or equal to 600 and less than 700 we will return a snowflake meaning snow then we have group 700
if our weather ID is greater than or equal to 700 and less than 800 we'll return some fog Emoji 800 exactly means a clear sky we can display the
sun if our weather ID is strictly equal to 800 exactly we'll return a sun emoji anything within the 800 range means
clouds so if our weather ID is greater than or equal to 801 800 means clear sky so with this group code it only goes up to 809 if our weather ID is less than 810 return acloud then let's add a default in case we get a weird weather code default return I don't know a questionmark we get some unknown weather phenomena UFOs or something I don't know okay and I think that should be everything let's close out of this close out of these functions and now if I were to type in Miamiand get the weather in Miami it is 60.3 De F humidity 81% there's overcast clouds and we get a cloud Emoji because it's cloudy let's try Dallas we have a clear sky 45° fah humidity 63% clear sky andwe get a sun emoji all right everybody so that is a weather app that you can make using Java JavaScript HTML and CSS