+ All Categories
Home > Documents > # M a k e W i t h M a y d m€¦ · In this activity, we will write HTML to create a container and...

# M a k e W i t h M a y d m€¦ · In this activity, we will write HTML to create a container and...

Date post: 29-Jun-2020
Category:
Upload: others
View: 1 times
Download: 0 times
Share this document with a friend
13
In the past two activities we have learned HTML and CSS, two of the three languages that are most commonly used to build websites. In this activity, we will play with the third language of the web, JavaScript, to create an animation. We highly suggest completing MakeWithMaydm Week 2 and 3 before working through this activity. In this activity, we will write HTML to create a container and place an image inside of it. Second, we’ll write CSS to style the HTML, and finally we’ll write a JavaScript function to move our HTML image across the container. #MakeWithMaydm Coding - JavaScript Classes and ids We learned about classes in the last activity. Classes allow developers to quickly stylize web page elements to look similar to one another. An id is related to a class and looks very similar, but can only be used one time. JavaScript JavaScript, often abbreviated as JS, is a high-level programming language that can run in a web browser or a server. The first iteration of JavaScript was created in 1995.. But what even is JavaScript?! Once an id name is created it cannot be created again. The advantage of this is that we can stylize elements in a unique way. Ids can also be called by <a> anchor tags. Let’s start with HTML. First we’ll create a <div> with an id name of “myContainer”.
Transcript
Page 1: # M a k e W i t h M a y d m€¦ · In this activity, we will write HTML to create a container and place an image inside of it. Second, we’ll write CSS to style the HTML, and finally

In the past two act iv i t ies we have learned HTML and CSS, two ofthe three languages that are most commonly used to bui ld

websites. In this act iv i ty , we wil l play with the third language ofthe web, JavaScript , to create an animation. We highly suggest

complet ing MakeWithMaydm Week 2 and 3 before workingthrough this act iv i ty .

In this act iv i ty , we wil l write HTML to create a container andplace an image inside of i t . Second, we’ l l write CSS to style theHTML, and f inal ly we’ l l write a JavaScript funct ion to move our

HTML image across the container .

# M a k e W i t h M a y d mC o d i n g - J a v a S c r i p t

Classes and ids We learned about classes in the last activity. Classes allow developers toquickly stylize web page elements to look similar to one another. An id isrelated to a class and looks very similar, but can only be used one time.

JavaScriptJavaScript, often abbreviated as JS, is a high-level programming

language that can run in a web browser or a server. The first iteration ofJavaScript was created in 1995..

B u t w h a t e v e n i s J a v a S c r i p t ? !

Once an id name is created it cannot be created again. The advantageof this is that we can stylize elements in a unique way. Ids can also be

called by <a> anchor tags.

L e t ’ s s t a r t w i t h H T M L . F i r s t w e ’ l l c r e a t e a < d i v > w i t ha n i d n a m e o f “ m y C o n t a i n e r ” .

Page 2: # M a k e W i t h M a y d m€¦ · In this activity, we will write HTML to create a container and place an image inside of it. Second, we’ll write CSS to style the HTML, and finally

<div id=”container”>

  <div id=”turtle-box”>

<img class=”animals”

src=”https://external-content.duckduckgo.com/iu/?

u=http%3A%2F%2Ffc06.deviantart.net%2Ffs70%2Fi%2F2013%2F0

02%2F5%2F3%2Fturtle_by_sweetlittlesmiles-

d5q7bm5.png&f=1&nofb=1”

alt=”turtle” />

 </div>

</div>

First , let ’s wr i te the HTML :

We’ve created two divs and given each of them a unique id name of“container” and “turtle-box”. Inside of “turtle-box” we’ve created animg tag that links to a transparent png of a turtle. Finally, we’ve giventhe img tag a class name of “animals”. (You can find your own imageby making an image search online and copying the image address.

At this point, we should onlysee the picture of our animal.

You won’t see the containerdiv until we add a little CSS

because it is anorganizational element,

unlike an image element thatactually places content on a

website. Your website shouldlook something like this with

only the HTML in place:

Page 3: # M a k e W i t h M a y d m€¦ · In this activity, we will write HTML to create a container and place an image inside of it. Second, we’ll write CSS to style the HTML, and finally

#container {  

width: 400px;

height: 400px;  

position: relative;  

background: blue;

#turtle-box {  

width: 50px;  

height: 50px;  

position: absolute;

}

.animals {  

width: 50px;

}

N o w , l e t ' s a d d t h e C S S :

We’ll style the container id, turtle-box id, and the animals class. 

Remember that in the previous activity (MakeWithMaydm Week3) we learned to style a class in CSS with a period before the classname. For example, we select the HTML class animals in CSS bywriting “.animals”.  

T o s e l e c t a n i d w e u s e t h e # s y m b o l . “ # t u r t l e - b o x ” .

We’ve told CSS to style our container idto be a square box that is 400 pixels wideand tall. The relative value in the position

attribute tells the browser to place thatdiv relative to its normal position. In this

case, it is placed in the top left corner ofthe browser window. 

The turtle-box id is set to be 50 pixelswide and tall and it’s position is set at

absolute. This means that the turtle-boxdiv uses the document body (where the

webpage starts) for alignment. 

Finally, we’ve set the animals class to be50px wide, matching the turtle-box id.

Page 4: # M a k e W i t h M a y d m€¦ · In this activity, we will write HTML to create a container and place an image inside of it. Second, we’ll write CSS to style the HTML, and finally

If your animal isn’t about 50pixels wide (that’s fairly small)and you don’t see a bluebackground

then double check the spellingof your id and class names

in the HTML and CSS.

Did you remember to add a“#” in CSS for id names and

a “.” for classes? Remember,the hashtag and period is

for CSS only.

Oftentimes, small spellingmistakes or missing syntax can

make our code behave inunexpected ways.

We’ve already created a static design on a website, which is prettycool! Let’s take it to the next level and use JavaScript to add

animation into our work.

To accomplish this, we’ll work through the JavaScript step by step.Before developers write any code they will take time to think about

the goal of the program and what requirements will be needed.

T h i s i s w h a t y o u r n e w s t y l e dw e b s i t e s h o u l d l o o k l i k e

O n t o J a v a S c r i p t . . .

Page 5: # M a k e W i t h M a y d m€¦ · In this activity, we will write HTML to create a container and place an image inside of it. Second, we’ll write CSS to style the HTML, and finally

Goal: To make an HTML image of a turtle moveacross the screen. Great! Remember, simple goals are best. If the goal is complex thendevelopers will break the goal into smaller mini-goals. Learning howto break big goals into smaller goals is the real trick to writingcomputer programs. For now, our stated goal is a good size so let’sdefine what we’ll need to accomplish this goal. We’ll call them ourrequirements.

Define the HTML element as a JavaScript variableDefine a variable to track the position of the elementDefine a variable that stores a value from the setInterval() methodWrite a function that will test if the position of the element shouldmove.

If the element shouldn’t move anymore then clear Intervalvariable.If the element should move then increase the position of theelement

Wrap all of that inside of a function so it can be called In other words, we’ll define a few variables for the HTMLelements and then test where the element is located andeither stop movement or initiate and continue the animation.We’ll wrap all of these commands inside of a function so thatwe can activate the script with an event listener.

L e t ' s D e f i n e O u r G o a l

R e q u i r e m e n t s

Page 6: # M a k e W i t h M a y d m€¦ · In this activity, we will write HTML to create a container and place an image inside of it. Second, we’ll write CSS to style the HTML, and finally

D e v e l o p e r T i p : Oftentimes, when developers are first learning they’ll type out codethey may not fully understand. They learn by playing with the codeto see how each line affects the behavior. So if you don’t completelyunderstand everything right now, that’s ok. Keep pushing forwardand then come back to review and you may be surprised at howmuch you understand on your second read through!.

A JavaScript function is a group of commands that are created to perform aspecific task. A function is executed, or ran, when an event listener calls it intoaction. (We call that invoking).  Event listeners can be something like a button or mouse click or a predefinedamount of time that passes.

Now that we have defined our goal and requirements let’s write some code.First, we’ll create variables to define our initial requirements.

Let ’s look closer at these f i rst three l ines.  In the f i rst l ine, we create a var iable cal led “elem ” , short

for element, that stores the HTML id “ turt le-box” .

“document .getElementById( ) ” is a JavaScript method thathelps developers manipulate an HTML id .

F u n c t i o n s &

E v e n t L i s t e n e r s

var elem = document.getElementById(“turtle-

box”);

var pos = 0;v

ar id = setInterval(frame, 10);

Page 7: # M a k e W i t h M a y d m€¦ · In this activity, we will write HTML to create a container and place an image inside of it. Second, we’ll write CSS to style the HTML, and finally

A JavaScript method is a pre-established function that helps developersaccomplish their goals.

Now that we have def ined our in i t ial requirements we wil lwr i te the frame funct ion which wil l check i f our image

should move across the window.

When we write our JavaScr ipt funct ion we wil l open thestatement with the keyword “funct ion” and then name the

funct ion. I t wi l l look l ike this :

J a v a S c r i p t M e t h o d s

The second l ine creates a var iable cal led “pos ” , short for“posit ion” and sets the value to 0 .    

The third l ine establ ishes a third var iable cal led “ id ”

stores a value from the set Interval ( ) method. The setinterval holds two parameters, a funct ion cal led frame

and an interval of 10 mil l iseconds.

Function parameters are “arguments” or values that are passed into and usedby methods. In this case, “setInterval()” is the JS method, while “frame” and “10”

are the function parameters.

F u n c t i o n P a r a m e t e r s

function frame () {}

Page 8: # M a k e W i t h M a y d m€¦ · In this activity, we will write HTML to create a container and place an image inside of it. Second, we’ll write CSS to style the HTML, and finally

Syntax is a word that refers to punctuation for programming languages.

JavaScr ipt offers a few different ways to wri te condit ionalstatements . In th is act iv i ty , we’ l l use what is cal led an i f-else statement. An i f-else statement looks l ike:

S y n t a x

The parenthesis after “ f rame” tel ls JavaScr ipt that frameis a funct ion. Funct ion parameters can be placed inside

the parenthesis , but they don’t always have to be. Thecurly braces wil l hold any statements that belong inside

of the funct ion. When you f i rst wr i te a funct ion i t iseasiest to wri te the curly braces r ight away so you don’t

forget to add them later .  

Remember, the smallest mistakes are often the ones tocause programs to fa i l .

Next, we wil l write a conditional statement, called an

if-else statement, inside the frame function.

Conditional statements allow our programs to perform different actionsbased on different conditions.

C o n d i t i o n a l S t a t e m e n t s

if (condition) {  // code that is ran if the condition is true} else {  // code that is executed if the condition isfalse}

Page 9: # M a k e W i t h M a y d m€¦ · In this activity, we will write HTML to create a container and place an image inside of it. Second, we’ll write CSS to style the HTML, and finally

Oftent imes the condit ion is def ined as a comparison with“<” less than, “>” greater than, or “==” equal to, ascomparison operators . For example the code snippetbelow (this is just an example) :

pos = 0; if (pos < 400) {   

// do something } else {  // do something else

}

would in i t iate the truecondit ion statementbecause pos equal to 0 .  

Alternat ively, i f pos hadbeen equal to 401 ( pos =401; ) then the elsestatement would havebeen in i t iated.

Our actual condit ion is going to use an equal comparison.We wil l wr i te this condit ional statement inside of thefunct ion frame.

Write this snippet of code on the l ine after “var id =set Interval ( frame, 10) ; ”

function frame() { if (pos == 350) {    clearInterval(id);  

} else {    pos++;    elem.style.top = pos + 'px';    elem.style.left = pos + 'px';  }

}

Page 10: # M a k e W i t h M a y d m€¦ · In this activity, we will write HTML to create a container and place an image inside of it. Second, we’ll write CSS to style the HTML, and finally

I n v o k e

Invoke means “ to ca l l in to act ion . ” I t ’s a word

deve lopers use to mean something c lose to “act ivate . ”

T h i s f u n c t i o n , w h e n i n v o k e d , w i l l c h e c ki f t h e p o s v a r i a b l e i s e q u a l t o 3 5 0 .

I f i t i s , then i t wi l l run the JavaScr ipt method

clear Interval , c lear ing the va lue in the id var iab le .  

I f the pos va lue i s not equal to 350 then the pos va lue

wi l l increment ( increase in va lue ) .

elem.sty le . top = pos + ‘px ’ ; increases the image e lement ’s va lue f rom thetop of the window.

e lem .s ty le . l e f t = pos + ‘px ’ ; increases the image e lement ’s va lue f rom the le f ts ide o f the window.

This means that the image e lement wi l l move down

and to the r ight across the window .

Now we are ready to wrap all of our code together inside of

a function that we will call moveAnimal() . We can call the

function anything we want , but it ’s best to choose a name

that describes what the function does . That way , someone

else can easily understand your code in the future . After all ,

code is written once and edited , or refactored , many times .

Page 11: # M a k e W i t h M a y d m€¦ · In this activity, we will write HTML to create a container and place an image inside of it. Second, we’ll write CSS to style the HTML, and finally

First , let ’s write the new

moveAnimal() function and

place all of our code inside

of it .

function moveAnimal() {//all of our JavaScript codewill go inside of these curlybrackets

}

We will wrap all of our variables and the conditional

statement inside of the moveAnimal function so that we

can invoke our JavaScript code with an event l istener in

the HTML . We will add an HTML button in a moment to

use as our event l istener .

function moveAnimal() {  var elem = document.getElementById("turtle-box");  var pos = 0;  var id = setInterval(frame, 10);  function frame() {    

if (pos == 350) {      clearInterval(id);    

} else {      pos++;      elem.style.top = pos + 'px';      elem.style.left = pos + 'px';    

}  }

}

T h e f i n a l J a v a S c r i p t c o d e

s h o u l d l o o k j u s t l i k e t h i s :

Page 12: # M a k e W i t h M a y d m€¦ · In this activity, we will write HTML to create a container and place an image inside of it. Second, we’ll write CSS to style the HTML, and finally

All we need to do is go back to the HTML and add a button

element . Buttons are very common on websites . Did you

know that they 're used as event l isteners? That means

when you click a button on a website , an event takes place .

<button onclick="moveAnimal()">Click to run</button>

I n o u r c a s e t h e e v e n t l i s t e n e r i s a b u t t o n ,

a n d t h e e v e n t w i l l b e o u r i m a g e mo v i n g

a c r o s s t h e s c r e e n !

Let's add the button at the top of our HTML, above the first div.

T h a t ’ s a l l o f o u r J a v a S c r i p t !W e ' r e a l m o s t t h e r e !

N o w a l l w e h a v e t o d o i s c l i c k t h eb u t t o n a n d w a t c h o u r t u r t l e s w i ma c r o s s t h e w i n d o w !

I f y o u r t u r t l e d o e s n ’ t mo v e a c r o s s t h e

s c r e e n d o u b l e c h e c k f o r m i s s p e l l i n g s o r

l e t t e r s t h a t s h o u l d b e u p p e r o r l o w e r c a s e .

Page 13: # M a k e W i t h M a y d m€¦ · In this activity, we will write HTML to create a container and place an image inside of it. Second, we’ll write CSS to style the HTML, and finally

Take a moment to write what you learned today so you’ll remember more

of your new JavaScript skills. Here are a couple questions to help youwrite about your experience today:

How do event l isteners connect HTML with JavaScript?

What was hard for you on the f irst try?

How did you overcome and succeed?

What personal touches will you add to your project?

# M a k e W i t h M a y d mY o u D i d I t !

Got Questions?

1.Look at the Maydm Template Pen 2. Search Engines are a great help!(Search JavaScript + 'your question here')3. Email us at [email protected]

Thanks for making with us! We want to see what you made!

Share a selfie of you and your site tagging @maydmtech and #MakeWithMaydm.


Recommended