Let’s start by going over some fundamentals.
That’s all. View code modifications on GitHub. Our HTML includes a link to our script file. Write the following code into your script.js file to make sure it functions.
Save the page, and then reload it.
Variables are descriptive names for data storage. Consider how you address people by name as opposed to using generic terms like “human” or “one head, two eyes, one nose…,” etc. Simply put, variables are just descriptive labels for data elements that are also user-friendly. Let’s look at an illustration.
Here, we’re creating a greeting variable and giving it the value “Hello world.” See how it almost sounds English: “let greeting be Hello world”? Now, a greeting can be used in place of the literal word “Hello world” because it contains the value “Hello world” in it.
The outcome should remain the same if you refresh the page. Variables are incredibly helpful for storing data in the real world, despite the fact that it may appear like we are doing more work to get the same outcome. Additionally, many forms of data, including strings, numbers, and other variables, can be stored in variables.
Observe how each line is punctuated with a semicolon (;). Although not strictly necessary (save in a few limited circumstances), using them is best practice, thus we advise you to do so.
The results might then be stored in a different variable after the values were stored in their respective variables.
Run it again; did you receive 5 this time? No? Go to the Console tab in the Chrome Developer Tools. Does it make a statement?
Ah, line 4 of the script.js file contains a mistake (notice the script.js:4 on the right corner of that red error message). Have you noticed the mistake on line 4? The alert is the one that lacks the final parenthesis. Correct it, then try running your code once more.
|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?|
*Less restrictive versions of these include == and! =, which make it possible to compare items that might not be of the same type.
“1” === 1 is false because it is a string instead of a number, but “1” === 1 is true.
We advise against using == and!, and to stick to strict equal/not equal (=== and!==).
Blocks of code that have names assigned to them so that we can reuse them are called functions. Let’s say that adding two integers is a frequent task on our website. The code mentioned above can be placed inside a function.
Watch how the function accepts two numbers (number1 and number2, officially referred to as the function’s parameters), adds them, and then “returns” the result, or sends it back to you. Although the “add” function is defined here, it is not being used. We must ‘call’ this code in order to use it. A function is called by simply writing its name and the “arguments” in parentheses (actual parameters).
Take yet another illustration. Think of a function that “alerts” anything that is sent to it.
There is no return value in this function, which has the name alertMessage and the parameter message (notice the missing return statement).
The function’s argument is the part that starts with “Hello World” when we call it alertMessage(“Hello World”) In terms of functions, this is merely the top of the iceberg, but it is sufficient to get us started.
You’d be fair to claim that repeating what we mentioned about variables makes this feel like more work to accomplish the same task. This will assist us in getting ready for more than just multiplying two integers together, though.
It will be clearer with an example. Suppose you want to display different messages to your users based on whether or not they are 18 or older. Your reasoning would sound like this in plain English:
You’re not an adult if you’re under the age of 18, else, you are.
If..general else’s syntax is as follows:
Every time we need to make a decision in the code, such as verifying that the users have input the correct data, we’ll utilize the if..else construct.
FirstName and LastName are the keys, and John and Doe are the values, in our sample object, fullName. We can use the dot (.) notation to get the firstName. The alert “John” will be displayed as follows.
As was already explained, objects can include both other objects and functions.
This time, we can convey a warning by saying: Once we move on to the next part, you’ll see this pattern employed all over again.
- Choosing HTML components
Let’s choose our submit button and add a “click listener” function to it first to accomplish that. When a button is clicked, an element to which a click listener has been attached will call the listener function.
The HTML element that matched the selector is returned as an Object by the function document.querySelector, which accepts the selector as an argument (remember that Objects are just containers for key-value pairs of data). The HTML element can then be saved in a variable and used for a variety of actions.
Just like when you pick IDs in CSS, the ID must be preceded by the pound sign (#). If it were a class name, you would use a period (. ), for example, submit button.
Try fiddling around with the development tools in general. It takes some practice, but once you get the hang of it, “debugging” (the process of determining what went wrong) is simpler.
- Incorporating a “click” listener
The click listener function is triggered when the specified HTML element is clicked.
But in order to make sure the code above runs correctly, we must make some changes to it before we try to run this.
Attempt running the CodePen snippet as well. The Developer Console will then open in the same window that you are reading this course in once you click the “Send Message” button. The console should display the text Button clicked.
In essence, we use the event parameter provided to our function, which holds the click event details (such as what was clicked, button characteristics, etc.), to stop the form from refreshing the page ()
Reload and save. Click the button once in the Developer Tools, Console tab.
- Obtaining values entered by the user
Our website has a form, but we haven’t discussed how we’ll extract the data a user might enter there.
Keep the document in mind.
We used the querySelector in the earlier section. It was used to choose HTML elements. We may use the same document because form inputs are nothing more than HTML elements and the data that a user may enter in those inputs is stored inside of the HTML elements. choose our HTML components using querySelector.
Then, we require knowledge of a critical fact. The ‘value’ key provides access to the data included in an HTML input’s value. Recall the objects? The ‘value’ key of the HTML input element object will store the text that is currently present in the element.
We will then offer comfort.
Check the emailText and messageText variables after logging the values from the input and textarea.
You probably noticed anything strange in the preceding section if you fiddled around a little. Despite the fact that the input fields for email and message state such things, you can pretty much type anything and have it accept it and print it.
You can even insert a message and email address that are both empty. That is not ideal. We’ll need to impose some limitations on what users can enter, particularly in the email area. For our purposes, it will be sufficient to see if the text typed in the email field has a “@” symbol. You’ll want to perform more thorough tests on the data in the real world.
We must create a validation function in order to validate emails. Checks are part of the validation, as was indicated in the section above. They could be verifications that the data is in the expected format, filters to remove any offensive terms from the text, or anything else. They provide a quick means of informing users about any mistakes they may have made when submitting their data.
In our example of validating email addresses, our check for “@” may capture cases in which users accidentally omit “@” or enter incorrect email addresses.
This function determines whether the character “@” is present in the supplied text argument email. The “if” and “else” you see are examples of a conditional, which is what is being used.
It can be understood as if true, it returns true. Otherwise, false is returned. Let’s test it by logging it into the console in our clickListener method.
Try it in CodePen and check the outcomes in the Developer Tools console of your browser.
Here, we start by looking at the email. We record the error message and return false if it fails (which is one way of preventing further execution of a function, meaning that our last console.log will not be executed).
We presume everything went according to plan and output a success message if the “if” block is not executed, which means a return false wasn’t encountered and the function is still running. Really lovely, huh?
Congratulations! Your brief course in web building is now complete. It’s been a very exciting few days, and we hope you’ve enjoyed this little adventure as much as we have.