💬“In some ways, programming is like painting. You start with a blank canvas and certain basic raw materials. You use a combination of science, art, and craft to determine what to do with them.” (Andrew Hunt)
What are we going to do today?
- Attach a ‘click’ listener to HTML form elements
- Fetch some user-entered values
The wait is finally over! Let’s get right to it.
Let’s begin by looking at some basics.
That’s it. We have linked our script file in our HTML. Just to make sure it works, write the following code into your script.js file.
Save and refresh the page.
Variables are friendly names that hold data. Think of how you call a person by their name as opposed to ‘human’ or ‘one head, two eyes, one nose…’ and so on. Variables are simply human-friendly (and descriptive) names for pieces of data. Let’s consider an example.
Here we’re defining a variable called ‘greeting’ and assigning it the value of ‘Hello world’. It almost reads like English–’let greeting be Hello world’–see? Now greeting holds the value ‘Hello world’ in it, and can be used instead of the literal text ‘Hello world’.
You could write:
Refresh the page and the result should be the same. While it seems like we’re doing more to achieve the same result, in the real world, variables are immensely useful for storing data. Variables can also be used to store different types of data such as numbers, strings, and other variables.
Also note how each line ends with a semicolon (;). This isn’t strictly needed (except for some specific cases), but it’s best practice to use them, so we recommend you do so.
You could also store the values in their own variables and then the result in another variable.
Try running it; did you get 5 again? No? Open the Chrome Developer Tools and go to the Console tab. Does it say anything?
Aah, an error in script.js file on line 4 (notice the
script.js:4 on the right corner of that red error message). Did you spot the error on line 4? It’s the alert that’s missing the closing parenthesis. Fix it, and try running your code again.
Comparison operators compare two things together. In English and other languages, we often ask questions like ‘Is it warmer today than yesterday’ or ‘Are these two buildings of the same size?’. The answer to these questions is either a yes or a no, and they’re usually comparing two things (today vs yesterday, building 1 vs building 2 etc). In programming terms, it is either a ‘true’ or ‘false’.
|Operator||Question in asks|
|===||Are the two things equal?*|
|!==||Are the two things unequal?*|
|>=||Is the first thing greater than or equal to the second?|
|<=||Is the first thing less than or equal to the second?|
|>||Is the first thing greater than the second?|
|<||Is the first thing less than the second?|
*There are less strict variants of these, namely == and !=, which enable you to compare two things that may not be of the same type.
“1” == 1 is true, but “1” === 1 is not true, as “1” is a string, while 1 is a number.
We recommend you stick to strict equal/not equal (=== and !==), and avoid the use of == and !=
Functions are blocks of code to which we assign a name so that we can reuse them. Say adding two numbers is a common operation for our website. We can write the above code inside a function, as follows:
See how the function accepts two numbers (number1 and number2, formally called the parameters of the function), adds them, and ‘returns’ the result; in other words, sends the result back to you. Here we’ve defined how the ‘add’ function should behave, but we’re not using it. To use this code, we’ll need to ‘call’ it. Calling a function is simply writing its name and using parentheses to pass in the ‘arguments’ (actual parameters).
Let’s take another example. Consider a function that ‘alerts’ whatever is sent to it.
In this function,
alertMessage is the function name,
message is the parameter and we have no return value (notice the missing return statement).
When we call it as
alertMessage(‘Hello World’), the ‘Hello World’ part is the argument of the function. This is just the tip of the iceberg in the world of functions, but enough to get us moving.
Getting back to the add function, we’ll use it as follows:
Did it run okay? If not, look into the console and see if you have any syntactical errors.
Repeating what we said about variables, this might again seem like more work to do exactly the same thing, and you’d be right in saying that. However, this will help us prepare for something more than just adding two numbers together.
An example will make it clearer. Suppose you wish to show different messages to your users depending on whether they’re 18 and above or not. In plain English, your logic would be as follows:
If age is less than 18, display “You’re not an adult”, else, display “You’re an adult”
The general syntax of if..else is:
We’ll use if..else whenever we’ll need to make a decision in the code–for example, making sure our users have entered the right data.
In our example object, which is called ‘fullName’, firstName and lastName are keys, and ‘John’ and ‘Doe’ are the values.
We can access the firstName by using the dot (.) notation. The following will show the alert ‘John’.
As mentioned, objects can have other objects and functions inside of them.
We can send an alert, in this case with:
You’ll see this pattern used all over once we move to the next section.
2. Selecting HTML elements
To do that, let’s first select our submit button and attach a ‘click listener’ function to it. When we attach a click listener to an element, it will call that listener function when the button is clicked. To be able to select our button, we’ll give it an ID attribute with a unique ID in our HTML file.
document.querySelector takes the selector as its parameter, and returns the HTML element that matched the selector, in the form of an Object (remember that Object are just containers for key-value pairs of data). We can then store this HTML element in a variable, and perform all sorts of operations on it.
Notice how the ID needs to be prefixed by the pound character (#), just like when you select IDs in CSS. If it were a class name you’d use (you guessed it) a period (.), like .submit-button
and check the output. If you see ‘undefined’ or ‘null’, it means something is incorrect.
In general, try tinkering with the developer tools. It takes time, but once you get the hang of it, figuring out what went wrong (‘debugging’) becomes easier.
3. Attaching a ‘click’ listener
But before we try to run this, we’ll need to make some changes to the above code to make sure it runs properly.
You can also try running the CodePen snippet. Click the ‘Send Message’ button and then open the Developer Console in the same window as the one you’re reading this course in. You should see the text Button clicked in the console.
Essentially, we’re taking the event parameter supplied to our function, which contains the details of the click event (like what was clicked, button properties, etc), and preventing the form from refreshing the page with event.preventDefault()
Save and reload. Open the Developer Tools, Console tab and try clicking the button.
Hurray!! It works.
4. Getting user entered values
Remember the document.querySelector we used in the previous section? We used it to select HTML elements. Since form inputs are nothing but HTML elements, and the data that a user might enter in those inputs is stored inside of the HTML elements, we could use the same document.querySelector and select our HTML elements.
Then, we need to know a crucial piece of information. An HTML input’s value, or the data inside of it, can be accessed via the ‘value’ key. Remember Objects? The HTML input element object will have a ‘value’ key that holds the current text inside of the element.
Finally, we’ll console.log the values from the input and textarea and see what we’re getting in the emailText and messageText variables.
Perfect! Did you see how the message just logs, flawlessly? Beautiful, we say. Instead of just printing the emailText and messageText, we’ve formatted it a bit using
console.log('email:', emailText, …) which will print it nicely with the label email: printed as is.
It is possible that you might see some errors at this point. Just go back and make sure you type it exactly as it is. Play around and try different inputs. Did you notice any issues?
Pro tip: It is important to make mistakes. You should get used to seeing error messages and knowing what they mean. It might feel a bit cryptic in the beginning, but practice is the key. So whether you get it right straight away or after a bit of trying, there’s always something to be learned.
If you played around a bit in the previous section, you’ll have noticed something weird. Although the input fields say email and message, you can pretty much enter anything into it and it would still accept and print it.
In fact, it even allows you to enter empty an empty email address and message. That’s not good. We’ll need to set some restrictions for what gets entered, especially the email field. For our purposes, checking to see if the text entered in the email field has an ‘@’ character will do. In the real world, you’ll want to do more stringent checks on the data.
For validating email, we need to write a validation function. Validation, as mentioned in the previous section, are checks. They could be checks to make sure the data is in the format we expect, or to filter any unwanted words from the text, or anything else. They serve as an easy way to let the users know about any errors in their data submissions.
In our email address validation example, our check for ‘@’ might catch the instance where our users forget to type ‘@’ or mistype their email addresses.
This function checks if the supplied text parameter email contains the ‘@’ character. It’s using something called a conditional (the ‘if’ and ‘else’ that you see). You can read it as, if yes, it returns true. Otherwise, it returns false. Let’s test it in our clickListener function by logging it to the console.
Try it in CodePen and view the results in your browser’s Developer Tools console.
Here, we’re first checking the email. If it fails, we log the error message and return false (which is one way of preventing further execution of a function, meaning that our last console.log will not be executed).
If the ‘if’ block are not executed (which means return false wasn’t encountered and the function is still running), we assume all went well and display a success message. Pretty sweet, huh?
Did you get it right? Great job! If not, just look carefully. You’ll find the bug. Remember, debugging is a critical developer skill!
Congratulations! You’ve reached the end of your web development short course. The last few days have been very exciting, and we hope you enjoyed this little journey as much as we did.
We’re proud of you for sticking till the end, and we hope this is just the start of your wonderful journey in web development.
So we’re finally at our last daily challenge. Are you excited about the vast world of web development that lies beyond this short course? We sure are!
Here are the tasks for today’s challenge:
1. Similar to our
emailValidate function, write a new function
validateNSFW (Not Safe For Work) that will take in the
messageText and return true if the message is safe for work. The function should return false if the text contains the word ‘crap’. You may use .includes() function for the task.
Use the previously written function and plug it into the
clickListener function similar to how we did it for
messageValidate, showing an error when
👋Departing words - Goodbye for now!
Today was the home stretch of this course, and we’re immensely happy that you made it through. It certainly wasn’t easy, and we hope you learned and enjoyed the experience.
There’s no day six to this course, so this is a farewell for now. But we like to think of this as the start of something interesting, a new beginning for you. If you decide to take up web development as a career, years later you’ll look back to this moment when you successfully created your very first website and made it both beautiful and functional.
If you’d like to stay updated about new and interesting topics on web development, we recommend you check out our blog! Finally, remember that whatever happens, never stop learning! See you again!
Q. This tutorial felt more difficult to grasp than the previous ones?
Q. Shouldn’t we use ‘function’ to write functions? That’s how it was written in some examples I read online.
Q. We used a click listener in the course. What if I want to detect a double click? Should I wait for two clicks?
A. No, there’s an event called dblclick. You can have an event listener listening for this event (using the element.addEventListener(eventName, listenerFunction) syntax). There are a lot of other useful events you can listen to–hover, scroll, keyboard key press etc.