Hello and welcome back,
Why not so great?
When we paint together, among the things that we should do is sell the painting. What if after I hand you the colours I go and sell the painting? That would be stupid, that would totally ruin our team work.
This is why we should not rely our JS code to do everything when it is read.
Why is great?
Let’s consider that we work on the painting, I give you the colours and then I wait long enough for you to finish. Then we sell it. This is great, this is how it should be done… but… it has happened like this by luck. If I would have waited less it would have been too soon. If I would have waited longer we would have been stuck. So, this is great but not so great.
How can we stop this from happening?
Instead of placing all the code in the file and make it look like this:
draw the horizon line
draw a tree
paint the sky with blue
paint the bark with brow
sell the painting
Let’s make it somewhat like this:
if the horizon line does not exist draw it;
paint the sky in blue;
draw a tree;
paint the bark with brow;
This will split our code into functions and although the functions are read by the browser when they are received they are not run until we call them. What’s even better is the fact that we can dictate the order very easily.
it is just a line changed. What’s even better is that now we can draw 2 trees without copying everything again! Just imagine how easy it is to just call functions to do the work wherever you need them to.
But where do we actually call them?
Now that’s a great question! There are multiple answers to this question:
- In HTML when an action is performed, like this:
<div class=”red leaf” id=”second_leaf” onclick=”draw_tree()”>second leaf</div>
The onclick is called an event. More events can be found here.
- When the page is loaded. This is more difficult to understand but easier to use. What we need is something that embraces our code and knows what to call for when the user performs events on the HTML tags used. We will call this thing “jQuery”.
- In the JS file write only the following code
alert(“I don’t know how to draw a tree but I have this nice message”);
- In the HTML file replace <div class=”red leaf” id=”second_leaf”>second leaf</div> with <div class=”red leaf” id=”second_leaf” onclick=”draw_tree()”>second leaf</div>
- Save both files, refresh and click on the red leaf.
Tomorrow we will learn the difference between a function and a property.