you are a user or developer of WordPress sites, or you intend to learn it, you may want to improve your pages and provide them with more capabilities and effects than the template you use on your site allows through JavaScript codes.
We can say that adding code directly to your website pages is not easy, especially if you are a beginner in WordPress. So, in this article, we will shed light on what Javascript is, and explain to you in a simplified manner how this language works, and how you can use it within the WordPress system to add dynamic, interactive elements to your site safely and without affecting the site’s performance.
Javascript – Overview
JavaScript is one of the most popular programming languages in the world, and it will benefit you most if you are a WordPress developer. It acts as a client-side coding language for front-end JavaScript development and is used in almost every website on the Internet.
JavaScript has also evolved into a back-end Javascript language using Node.js, putting it in direct competition with PHP.
Therefore, whether you are a front-end or back-end developer, learning JavaScript will definitely benefit you. Note that in this article we will focus on JavaScript that runs on the client side.
JavaScript, usually shortened to JS, is known as the scripting language for Web pages. JavaScript works with object-oriented programming
Explanation: Object-oriented programming, also known as OOP, is an advanced style of programming that relies on defining code in the form of objects.
Any object has Properties that express the variables it deals with, and Functions that express the tasks it performs on these variables. These organisms are governed by several principles, the most important of which are the principle of encapsulation and inheritance.
- Encapsulation : is restricting the process of direct access to data or variables defined within an object. This data can be accessed only from within the object itself or through the principle of inheritance, that is, by creating a child object for this object.
- Inheritance : It is a method that enables you to create a son or heir from an object that inherits specified characteristics from it. The child object can access the special variables defined within the father, and the opposite cannot happen. As I do all my code inherits all global variables global scope.
In traditional programming, all the required operations or functions were written in the program from top to bottom and were executed according to the chronological order of their arrival from the first line to the last line in the program. While in object-oriented programming (OOP) the code is divided into objects or objects, each object has its own set of properties or variables and functions.
Which means that the script is in the form of multiple boxes (each object is a box, so to speak) that work and interact with each other to accomplish the required tasks.
Because objects in JavaScript rely on the principle of data hiding and inheritance, this gives high security to the code, reduces the occurrence of errors and reduces the size of the code. So you can call the same object and reuse it in any part of the program.
Note: If you feel that the previous concepts are new to you and difficult to understand, do not worry. When you apply these concepts practically in the code, all these matters will become clear to you and it will be easy for you to understand them. JavaScript is a flexible, dynamic, and easy-to-learn language.
In general, JavaScript is used to fully control the behavior of the browser, and it gives websites dynamism and makes them interactive, so that you can do a specific thing when an event occurs. We can say that if HTML and CSS are the body and structure of the page, then JavaScript is the soul that gives movement and interaction to the page.
What can JavaScript do?
Generally JavaScript is used to control the behavior of a web page. For example:
- Adding dynamic animated elements: JavaScript brings life to the web page, through which you can, for example, animate an element when you access it, show dialog boxes after a certain time, animate texts, change site colors according to the time (such as night mode), create timers, create Animated slides, and much more.
- Changing the content of a web page. JavaScript can change any part of the page content. The closest example of this is multilingual sites, where JavaScript can know the browser’s language and adjust the site’s language based on it.
- Performing calculations: Like any programming language, JavaScript can be used to create advanced web applications such as age calculator, body mass index calculator, pregnancy calculator, and even very complex calculations with ease and high speed.
This is not a complete list of what you can do with JavaScript. JavaScript can really do anything you can imagine in a web page and control the behavior of the entire page. Below is a quick list of the effects that JavaScript accomplishes:
- Make drop-down menus like the main site menu
- The button to go up the site works quickly if you are at the end of the page
- Show the user real-time messages based on what they do
- Storing user activity, and fetching some of his data from the browser in order to develop the site
- Secure input fields by not allowing certain characters to be typed, or forcing the user to enter a certain number of letters and/or words
- Open the camera and microphone and then send them to another person via the WEBRTC feature (creating a video and audio chat system). It is also possible to photograph the desktop with the same technology.
- Building websites via drag and drop, which is what we see when using a tool like Elementor or wb-bakery to build WordPress pages.
- Protecting website content against copying, such as preventing text selection, preventing the use of the right mouse button, and preventing the use of copy buttons from the keyboard
- Create games on the web
- Create 2D and 3D animation
- Fetching data from other sites via API, such as user data from Twitter or Facebook via JSON and AJAX
The WordPress system uses the JavaScript language very extensively, and it even supports one of the most important JavaScript libraries, which is the JQUERY library, as the WordPress version includes the latest version of JQUERY.
Definition: JQUERY: It is an open source library that facilitates dealing with JavaScript. It greatly shortens JavaScript codes and saves the programmer time and effort. It also provides faster page loading and helps improve search engines. Therefore, it is widely used by web designers.
Before discussing how to add and run JavaScript code on your WordPress site, we must first clarify how JavaScript works in general. Therefore, we will divide the following paragraphs into two main sections:
- The first section – explaining JavaScript for beginners. In this section we will explain how to write JavaScript codes, and explain the concept of functions, variables and constants, loops, objects, arrays, DOM and BOM elements, and the correct place to add the code so that it works well without affecting it. On the rest of the pages.
- Section Two – Using JavaScript in the WordPress structure. In this section, we will explain how JavaScript works within the WordPress system, and we will explain how to add JavaScript code to the site in more than one way, in addition to how to modify any part of your site (adding to the site, deleting from it, or modify it) correctly.
If you want to start learning the JavaScript language through an integrated educational course, you can purchase an application development course using the JavaScript language at Hassoub Academy, which provides 54 hours of training with support and guidance from a specialized team that helps you from the beginning, and at the end of the course you obtain an accredited certificate. From Hassoub Academy.
JavaScript explanation for beginners
By learning JavaScript, it will then become easier for you to learn any programming language very quickly. As most programming languages are similar in terms of functions and the way the code is written. The JavaScript language is very flexible and easy to learn, as we mentioned.
Before learning JavaScript, you must have an intermediate knowledge of HTML and CSS. You can learn more about each of them by reviewing our following article explaining HTML and CSS and how to use them and modify their codes completely .
Where is JavaScript code written?
Any JavaScript code can be added to your site in two different ways:
The first method: inside the HTML file.
This is done by placing the code between the open and close tags of the script element, as the following code shows:
The previous code changes the content of the element bearing the id named test to the text I am a javascript programmer.
It is possible to place the JavaScript code anywhere between page elements in the Html file, but it is preferable to write it at the end of the page as shown in the previous image to ensure that the page does not crash if any errors occur.
Explanation: JavaScript codes are executed line by line while downloading page content. When the browser encounters a JavaScript code, it will stop parsing and displaying the page and will execute the JavaScript first, then it will complete the download process.
For this reason, if there is a problem with one of the lines of JavaScript code written at the beginning of the page, the rest of the page will not work and will crash. Also, the page will display slowly if you put all the JavaScript code at the beginning. Therefore, placing unnecessary code at the end of the page ensures that the entire page is loaded first and the code is executed after that.
The second method: Put the JavaScript code in an external file
In fact, this method is considered the preferred method, especially if the codes are very large. In this case, you need to create a file with the js extension, put the code inside it, save it in an external path, and call this file inside the Html page, as the following steps explain:
Assuming that we will place all the JavaScript code in a file named main.js located in the same directory as the HTML file.
1. We call the JavaScript file in HTML. This is done by writing the path of the JavaScript file within the src descriptor of the script tag as follows:
2. We create a new file with the js extension. In our example, we created a file named main.js, which is the same name as the file that was specified in the previous code, then we put the following code inside this file. As the picture shows:
Note 1:
Note that writing codes in the external JavaScript file is done directly, without the need to add codes between two tags:
>script> </script<
Note 2 :
You must pay attention to the file path carefully, as the previous file must be placed side by side with the HTML file. When the file is placed inside another folder with the name script, for example, the name of the file passed inside the HTML file will then be as follows:
Output in JavaScript Output
JavaScript can output results in different ways. By output we mean the results that the code aims to process and output for the user to see.
Here are the ways to display data in JavaScript:
1- Inside HTML elements or what is known as the DOM
JavaScript can display data anywhere on a web page, and it can modify the content of an element, delete it, hide it, or change its style or format.
HTML elements are called DOM, which stands for Document Object Model, which means the HTML elements on the page, such as (head, body, p, div) and any other element within the page.
Examples and methods of modifying HTML elements via the DOM are:
- element.innerHTML, used to change HTML elements inside a parent element
- element.innerText, used to change texts inside elements
- element.style.property, to change the style or appearance of any element, change the word property with any css element such as color or background…. etc.
- document.createElement(element), to create a new element on the page. The word element is changed with the element to be created, such as div, p, etc
- document.appendChild(element), to place a new element inside a parent element
- document.write(text), to change all page content with new text
- document.getElementById(id), to search for an element with a specific id
- document.getElementsByClassName(name), to search for an element with a specific class.
- Illustrative example:
The previous code changes HTML elements inside the element with id as test. It should be noted that the word document is one of the elements of the DOM and means the entire page (the document), the word getElement is one of the elements of the DOM and means to fetch the element, and the word ById means by the id.
Explanation: If we translate the previous code into text, it will be as follows: Search the entire page, which is what document refers to, for the element that has a specific id, which is what getElementById(“test”) indicates, and change the content of this element, which is what innerHTML refers to.
innerHTML can be changed with innerText to change only the text displayed inside the element. As for innerHTML, it changes everything in the element, including the HTML codes, not just the texts.
The element can also be fetched by its class name by replacing the getElementById instruction with the getElementsByClassName instruction. The element can also be selected using the same method for selecting elements in CSS, as the following example shows:
So you can write the id or class of the element instead of the word #id, just like choosing any element in CSS. So the selection is by id as we explained, and the selection is by the class as follows:
Note : In the case of getElementById or getElementsByClassName, we write the id or class of the element directly without the sign (#) or (.).
However, in the case of querySelector, we must indicate whether the element contains the id or class by (#) in the case of id and (. ) in the case of class.
2- In the Alert box
The alert box is a dialog alert box that appears at the top of the site to alert you of a specific event, and it contains an OK button. The alert box code is represented as follows:
Or it can be shortened as follows:
3- In the entire HTML page
This method deletes all the elements on the page and prints only the sentence or elements in the code. The code is represented as follows:
4- In the browser console
This method is used for educational or experimental purposes, and is useful for programmers to either catch errors or to experiment with the output before printing it on the screen. They are as follows:
To access the browser console, right-click on any page, then choose Inspect, then choose the console tab as the following image shows:
Variables and constants in JavaScript
Variables are a place or container to store data in memory for use when needed. There are three ways in JavaScript to declare the values of the variables in which you will store your data.
- var, is used to declare a new variable and its value can be changed or re-declared again.
- let, which is a new word that was added in the ES6 (2015) version and is an alternative to its predecessor, but it does not enable you to re-declare variables with the same variable names used in them again.
- const, used to declare constants whose values do not need to change throughout the program.
Illustrative examples of variables:
Considering that we have a product that is displayed on 10 pages, this product has a price, tax rate and shipping rate. If we want to change the price of the product, do we have to change the price in 10 pages?
Quite simply, this is the role of variables. Where a variable is created that holds the price, another that holds the taxes, and a third that holds the price of the delivery service. If we decide to change the price of the product, we do so only once, as we change the value of the variable and the new price is applied to all pages automatically.
The following code explains the task:
If you try the previous code, the output will be: 25
clarification
In the first line, we defined a variable prodPrice to store the price of the product and placed or assigned the value 20 to it.
In the second line, we defined another variable, tax, to store the tax value and assigned it the value 3.
In the third line, we defined a variable for the shipping price, which is dlvryCost, and assigned it the value 2.
In the last line, we added code to output the result of combining the three variables together and print the result in the HTML element that has the id named test.
Of course, you can extract the results using one of the other output methods that we explained above. For example, the alert message can be used to display the result instead of innerHTML, as follows:
The result in this case will be as the image below shows:
How to use variables in JavaScript:
- Declare a variable/or constant using the reserved word that expresses variables, as we explained, which is either var, let, or const, as needed. It is preferable to use let for variables and const for constants that contain information that will never change.
- Writing a name for the variable. The name of the variable in JavaScript must begin with the letters -, -, or $ only. A variable name can contain numbers only in the middle or at the end.
It should be noted that variable names are case sensitive, so the variable myname is not equal to the variable myName. - Assigning a value to a variable: You can assign a value to any variable by using the sign (=), which is known as the assignment operator, and then writing the desired value. It should be noted that it is possible to declare a variable at the beginning without assigning a value to it in the following form:
var prodPrice;
Then the value is later assigned to it anywhere in the code, so that one variable can produce different outputs depending on what is required of it. Where it is possible to assign a value to the variable after declaring it, as in our case, as follows:
prodPrice = 20;
Note that we did not write the reserved word var in the last line of code we wrote, because we had already declared the variable. A variable is declared only once in each object.
Remember that if we declare the same variable again using let, we will get an error indicating that the variable has already been declared before. - End the line with a semicolon (;) Note that every code in JavaScript ends with a semicolon. This comma is important to indicate the end of the code, and forgetting it may cause an error (in new versions of JavaScript, the comma may not be written in some cases, as It no longer strictly requires a semicolon, and may automatically insert it when needed)
- To display the value stored in a variable: We write its name directly without any single or double quotation marks. It can also be combined or its value combined with the value of another variable using the (+) sign, which is called the addition operator. Not only that, but all mathematical operations can be easily performed on it using known regular arithmetic operators such as (- for subtraction, * for multiplication, and / for division).
You will learn more about variables in the following lines.
Data types in JavaScript
JavaScript is a very flexible language and can identify a data type by the way it is written or declared. Each data type has a different way to write it. Variables in JavaScript can hold or store any type of data, which in turn leads us to learn about data types in JavaScript, which include:
Texts Strings
To assign text to a variable, the required text must be written between double quotation marks (“TEXT HERRE”) or single quotation marks (“TEXT HERE”), as the following example shows:
or
Numbers: To assign a number to any variable, the number is written directly, without the single or double quotation marks, as follows:
Note:
If the number is enclosed in quotation marks, in this case it is considered a text string and not a number, and you will not be able to perform mathematical operations on it until it is converted to a number.
Boolean values
In JavaScript – and all other programming languages - there are only two logical values. The element is either true (TRUE) or false (FALSE).
To represent this in our previous example:
The sign (===) is called the comparison operator. It is used to compare the values of two variables and returns a logical value, either true if the two values are equal in value and data type, or false if they are not equal. It is different from the assignment sign (=), which attaches a new value to a variable.
When running the previous code, the result will be false, because the previous code tests whether the value of the variable prodPrice is equal to the value of the variable tax, or rather we tell it whether 20 equals 3. Notice the image of the result of running the previous code:
Note: There is another comparison operator used for logical comparisons, which is binary equality (==), which is considered less strict than the operator (===). If the variable values are of different types and have the same value, for example the number 38 and the text “38”, then the values are considered equal and we will get The result is true if it is compared using the operator (==)
Arrays
An array is a variable of a special type, which can contain more than one value at a time. Arrays can be declared in many ways, but the preferred method is to use square brackets [] in the following form:
To create a static array that stores the names of friends I would write the following:
In this example I created an array containing 4 elements. I stored in each item the name of my friends. You display all the values stored in it. Executing the previous code will show the following result:
The values stored in the array can be accessed in more than one way, but what you should know now is that each element inside the array has its own directory called index. This directory expresses the order or location of the element within the array.
Arrays in JavaScript are indexed on a zero-based basis, meaning that the first element, Ahmed, has an index equal to 0, and the second element, Mohamed, has an index equal to 1… and so on until the end of the array.
Thus the index value allows you to access each of the elements within your array. The value of the element in any directory can be extracted by placing [index] after the array name.
In the previous example, we can print each of the values stored in our myFriends array on a separate line using the following code:
Note that here we used the DOM element we talked about, innerHTML, to print the result on the HTML page inside the element bearing the id named test. Note also that we used the sign (+=), which is called the addition assignment operator, after displaying the first result, because (=) only deletes the previous contents of the element and assigns only the new value, while (+=) adds the new value to the HTML element without deleting it. Previous content of it.
The symbol </br< is used to add a new line in HTML, and to merge any two values together, we use the plus sign (+). If the values are numbers, they are added together, but if they are text values, the values are merged together. The result of the previous example is as follows:
Of course, it is preferable to print the elements of arrays using one of the loops (for loop, forEach, While, Do While), which provides us with various ways to navigate through the elements of the array. We will also explain this shortly when explaining recursive structures in JavaScript.
Objects
JavaScript, as we mentioned in the introduction, relies on the principle of object-oriented programming (OOP), which enables us to define objects or objects within the program. An object consists of a set of properties. So that each property is in the form of a pair consisting of (the key or name of the property, Key, and the value of the property, Value).
As you will notice, objects are somewhat similar to arrays (actually arrays are a special type of object), except that the objects are represented between curly braces {} and each of their elements has a key and a value. Instead of writing the directory index, write the key followed by a colon (:) and then the value of this key.
The JavaScript language contains a number of predefined objects that can be used directly (such as the Date object, and the Array object as we mentioned…) In addition, you can create and define your own objects. For example, to create an object that represents the user and has 4 properties (name, nickname, age, and gender), we write the following code:
Note that we use [] tags to represent arrays, while we use {} tags to represent variables. Also note that the object must have keys that represent the value stored in it, such as firstName, lastName, age, and gender.
To display the value of any of these keys, the name of the object is written, which in our example is user, followed by a period (.) and then the key. In the previous example of knowing a person’s name, this is represented as follows:
The result of executing the previous code is as follows:
Note: The value of a property can be a function instead of a variable. We will explain in detail the concept of functions in JavaScript in the next paragraph.
I think you now understand the difference between arrays and objects, and you know that the plus sign (+) is used to add if the values are numbers and to combine if the values are something else. The sign (+=) adds a new value to the element without deleting the old values, while the sign (=) replaces the old value with a new value, and the sign (===) is used to compare two elements.
Note: You can find out the type of any variable, any element, or any value in JavaScript by typing typof() which returns you the type of the variable passed in parentheses. In our previous example, if we wrote the following code:
The result will be: object
Exercise: Write variables that hold different types of data and identify each variable type using typof() as you learned. Knowing the data type is very important in any programming language, and objects and arrays are among the most important things to learn, as JavaScript depends primarily on them. Even texts are treated with the same principle as well. So that every letter in any text string has an index number that can be changed or deleted by it.
Looping in JavaScript
The purpose of loops is to repeat the execution of a set of instructions multiple times. It is also mainly used with arrays and objects in order to access all elements of these arrays and objects. Such as making a loop that extracts all the images on the site, or extracting all the texts that contain a specific word, or making an animated slider that repeats the display of a group of images or graphics, or fetching the page content from the API using ajax or json and other tasks..
There are several types of loops in JavaScript that can be used as needed, and we will explain the differences between them through examples:
Simple for loop :
The simplest form of a loop is to repeat telegrams a specified number of times (from one specified number, to another specified number).
For example, to print numbers from 0 to 10, we write the print instruction using the for loop as follows.
The previous code is very simple. In the beginning, we start by writing the word for, followed by the parentheses (). Inside the parentheses, a variable is declared and given an initial value to start from (this variable is called the loop counter). In our case, we created a variable named i and assigned the number 0 to it to be the beginning of the loop, then we put a semicolon. (;).
In the second part, inside the parentheses, we set the condition for the loop to terminate or stop running. Which is when i is smaller or equal to 10.
After that, we asked that the loop counter i be incremented by a specific value, which here is 1, at each iteration or cycle of the loop, which is expressed by the two plus signs after the loop counter i++ (1+i can also be used. Both are correct ). Then we opened braces {} and requested that the value of i be printed in each cycle within the HTML file as we explained previously.
Note: It is very important to specify the end point for each loop, otherwise the loop will not stop and we will have an infinite loop that will cause the browser to freeze and perhaps the entire device.
Isn’t that great? Suppose you have a select element in your HTML that expresses a drop-down list that enables the user to select their year of birth. You want to add a specific year group to it (from 1900 to 2021). Are you going to write the addition instruction manually for each year? Of course, if you think like programmers, the answer will definitely be no. But you can instead execute the following code to complete the addition process simply as follows:
The following image shows what the HTML code looks like:
The following image shows the result of executing the code:
Back to matrices. Did you remember the last thing we said in explaining arrays, which is that the best way to access array elements is through recursion rights? As we explained previously, the array contains a set of elements or values that we passed inside the [] signs, and each of these elements has an index indicating its location in the array, so the first element carries index 0 and the second index 1…. etc.
Returning to the example of arrays, the best way to extract or display all the values contained in our myFriends array is to use a for loop.
Note the following example:
The previous code will output or display all the elements in the myFriends array as we did previously. But the previous code was too long.
Note here that the statement myFriends.length gives us the length of the array. Length is an important property of arrays and you will need it frequently to know the length of arrays, strings, etc. We used it here to tell the iteration loop to stop when the value of the array counter i becomes completely smaller than the length of the array (why didn’t we say less than or equal to?)
because the length of the array is the number of its elements, which in our example is equal to 4. While the index of the array begins with the number 0, i.e. Element No. 1 will have an index equal to 0, element No. 2 will have an index of 1, and so on. Therefore, the index of the last element will be the length of the array minus 1.
loop for in
It is like the previous one, except that it is brief, meaning that you do not need to write a counter that represents the beginning and end of the loop, but the start and length of the loop are determined automatically according to the length of the array or object that you passed to the loop.
To understand the difference between these two loops, notice how the previous example is implemented:
The result of executing this code will be exactly the same as the previous code, which is as follows:
For of loop
Like the previous two, it is written in a more concise form, and it also wraps around strings, arrays, objects, and any iterable element. It is represented as follows:
Note that in this case we put the variable i in the print instruction only to output the value of the element because i in this case does not take the value of the directory or key, but rather takes the actual value stored in the array or object. For this reason, we did not put the name of the array as in the for and for in loops. . (With practice, you will discover that each loop has features and locations that make work easier and simplify the code.)
While loop
While executes the code inside it as long as the condition passed to the loop is true. Its general form is as follows:
This statement means: As long as the condition is true or equal to true, repeat the code written between {}. Examples of a while loop are:
The previous code prints numbers from 0 to 9. The code can be translated textually as follows: As long as the value of the loop counter i is less than 10, print i and then add or add to it the number 1. Note that we created the variable i and assigned it an initial value of 0 so that the loop starts from Has.
Note: The code executed within a while loop must always contain an instruction that changes the value of the loop counter so that the condition in an iteration becomes unfulfilled (false), otherwise we will get an infinite loop.
There is another form of while loop which is called do while . The difference between them is that the first tests the condition first and then executes the code, and the second executes the code first and then tests the condition.
To execute the previous code in a do while loop, the code is as follows:
The previous code executes the code written inside {} after do as long as i is less than 10.
Functions in JavaScript
Functions or functions are one of the basic building blocks of JavaScript. A function is a block or block that contains within it a group of statements that perform a specific task. The code inside it can be accessed by calling it by its name, as we will explain shortly.
The function can take some variables as arguments or as inputs to which it is passed in parentheses after the function name, as we will see shortly (called function parameters). The function usually returns output outside the function. Variables can also be defined within the function code as needed. They are called (local variables), meaning they are encapsulated or packaged inside the function and specific to it and cannot be accessed from outside the function.
The function can access all global scope variables, that is, those that are placed in the code page without encapsulation, or those that are placed in the parent function. This is what we talked about in the principle of inheritance.
How to write functions in JavaScript
Functions in JavaScript are declared with the word function, followed by the function name, then parentheses () followed by curly braces {}. Between these parentheses, the implementation for this function is written. The implementation is the programming code that performs the function or task that the function is required to achieve. As the following code explains:
The previous code is a simple function whose function is to write the phrase Hello world in the alert box. however! If you run the code, the function will never work because you did not call it, or in other words, you did not ask it to run and carry out its task.
To call the previous function, all you have to do is write its name followed by parentheses (). The final form of the previous code is as follows:
The result of the following code will be as shown in the image below:
The main goal of functions is to break down the code and make it easier, in addition to saving time and effort. Functions can be called from anywhere on the page without having to rewrite the code again.
Function parameters or parameters
Parameters are variables that are declared inside function parentheses () when needed. It expresses the number and type of values that a function needs to perform its work. The actual values of these parameters must be passed inside the function’s parentheses () when called or called.
For example, the following function calculates the square root of any number passed to it as a parameter:
The previous code outputs the number: 9
The function here simply makes an iterative loop using a for loop, starting from the number 0. It multiplies the number 0 by itself, and if it is equal to the number passed to the function (parameter), it returns the new number to you. Otherwise, it multiplies the number 1 by itself. If it does not equal the parameter, it multiplies 2 by Same… and so on until you find two numbers that when multiplied together give the value of the coefficient, which in our example is 81.
The function will still multiply the numbers together in the order 0, then 1, then 2, then 3, then…. Etc. until you reach the number 9. When you multiply 9 by itself, it gives 81, which is what the function aims to reach.
Isn’t that wonderful! This is the power of programming, my friend. You have to find the idea and it will do wonders.
The conditional if statement here (which will be explained in the next section) stops the loop and returns the number when it gets it. Otherwise, the loop will run indefinitely and cause the browser to freeze, as we explained in the Loops section.
Then we called the function using: getSquareRoot(81) and passed the value 81 as a parameter to the function, and showed the result in the alert box that we talked about in the output section. Try the function by changing 81 to other numbers and see for yourself, then try doing other things with the functions.
It is possible to put more than one parameter in a function by separating them using a comma (,), as the following example shows:
The previous example multiplies any 3 numbers together. Using functions, you can perform very complex functions, such as difficult calculations that require a lot of effort. You can also perform other functions on your site and return different values.
Events in JavaScript
Events are things that happen in HTML elements through which JavaScript can interact with HTML and change certain things on the page or perform a specific action when they occur.
Examples of events that occur in HTML include:
- Onclick, which is the event that occurs when the user clicks on any part of the HTML page and is not limited to clicking on buttons on the page only as some people think.
- When you double click the mouse button ondblclick, this event occurs when you click twice in a row on the left mouse button, just like when you click on desktop icons in the Windows operating system.
- Onload , this event occurs when the HTML page has completed loading. It is always preferable to execute JavaScript codes after the pages have completed loading so as not to cause the site to crash if any error occurs. This is done by placing the code at the end of the page, as we explained previously. Or by calling the code inside this event.
- Onmouseover, this event occurs when you hover your mouse over a specific element such as text, link, image or anything else present within an HTML page.
- After the mouse moves away from the element onmouseout, this event is called after the mouse moves away from a specific element, such as the mouse moves away from an image or text.
- When the value of the onchange element changes, this event occurs when the input field changes when the user types something in it, such as when the user types a value in the search box and search suggestions appear.
- When the onfocus field is activated, which happens when you click on any input field to start typing.
- When any button is clicked onkeydown, this event occurs when the keyboard buttons are clicked. It should be noted that each button on the keyboard has a specific number, for example the enter button has the number 13.
- When you remove your hand from the onkeyup button, this event occurs when you remove your hand from the button on the keyboard. Unlike the previous event which is called once the button is clicked.
This is not a complete list of all HTML events. Every change and movement that occurs in the browser has an event, such as sidebar scroll event, copy event, paste event, right mouse button click event. You can fully control browser behavior through these events and with more practice you can create professional 2D and 3D games.
HTML Events Reference to learn more:
https://www.w3schools.com/jsref/dom_obj_event.asp
How to execute any code when an event occurs in JavaScript
Events in JavaScript should call functions that have specific tasks. That is, every event that occurs can be associated with a function that is executed as soon as that event occurs.
There are two ways to do this, or rather to associate JavaScript codes with events that occur in HTML elements, and they are as follows:
1-Inside attribute in HTML elements
So that the event calls as soon as it occurs on a specific function to execute it, as the following code shows:
The following image shows the HTML page and how we called the getSquareRoot() function when the button click event occurred:
Note that in the HTML file we added a new attribute for the button called onclick so that the getSquareRoot() function is called when it is clicked. In the JavaScript file, we used 3 variables in the function:
1-The input variable is the input field in which the user types the number. Note that value returns the value within any input field.
2-The second variable is output , in which we put the element in which the results will be displayed.
3-The third variable, which is number, is used to fetch the value that the user enters by simply calling the square root calculation function.
Notice the last line in the code how we extracted the result from the for loop after subtracting 1 from it because the loop will do another cycle before stopping the code.
The result of the previous code is as follows after placing the number 112 in the input field and clicking on the Calculate Square Root button:
2-Inside the JavaScript file
In this case, we create an external file and write HTML codes in it without writing anything inside the HTML elements. We just call the file in the usual way. In this case, the previous code is executed as follows:
As you can see, we defined a variable btn that represents the button, and we called the function to calculate the square root when the onclick event occurred. In fact, it is preferable to use this method because it is better organized and the HTML is separated from the JavaScript.
Save the previous code in a file called main.js and call it in an HTML file as follows:
note:
The previous code can be done in the following way, as it is the new method in recent versions of JavaScript):
Note that we used the word addEventListener and then attached the click event to it. Then we passed the function directly by separating the event from the function with a comma (,) and enclosing the event inside quotation marks (double or single). Note also that we did not write the word function. We were satisfied with the parentheses, then the =< symbol, then the curly braces {}, and then the last parenthesis for the word addEventListener.
Generally, whatever method is used to generate the event in JavaScript will work. But the last method is preferable, as it is possible that you do not have the ability to edit HTML files as in WordPress, so all you have to do is know the id or class of the element and then create an event for it as we explained.
All other events are implemented in the previous way, meaning you can replace onclick with any of the events mentioned above.
The conditional statements if, if else, and else
They are statements used to verify a condition and execute specific instructions when this condition is met, such as (verifying that the item exists, verifying that the item has a specific color or background, verifying the time and date). In all cases, it is verified that the value of a condition is true in order for the code to be executed. Its general form is as follows:
The code is translated into text as follows: If the condition is met, execute something, else, or else, execute something else.
We would say, for example, if the time is from 12 am to 12 pm, show the user the message “Good morning,” and otherwise tell him “Good evening.” This is implemented programmatically as follows:
Note that the symbol && means AND, meaning that both conditions must be met to execute the code. The result of the previous code is as follows:
I think the code is self-explanatory, but I would like to clarify that the variable currentOur holds the current hour (hours only), which is what new Date().getHours() expresses, which is one of the JavaScript functions ready to fetch the device’s clock in real time.
In the previous method, we can make the site work in night mode at night (a specific design with a black background) and in normal mode during the day. The code can be modified to become as follows:
The previous code changes the website background to black if the time is from 12 at night (00 indicates 12 am) to 12 noon. And green for the rest of the day.
Note that the document.body.style.background directive selects the body element from the HTML file and then assigns a backgruond style to it. Any style can be added to any HTML element in a similar manner.
Advanced example of if and else if and else
Assuming that our site is accessed by three categories of users:
1- Children up to 18 years.
2-Adults from 18 to 21 years old.
3- Adults over 21 years old.
We have 3 types of content on the site, and we want the site content to change according to the age of each user. How is this implemented programmatically? The following code shows the simplest way to implement the idea. By referring to the attached example in objects, we defined the user object as follows:
The HTML file will consist of 3 div elements, each with a different color. We have allocated one for children in green, one for adults in yellow, and another for adults in red. The following image shows the HTML file:
In normal mode without running the code, the result is as follows:
But when you run the code and visit the page, what will appear is only the red bar, which is the content intended for adults. The reason is that we passed the value 31 to the age key via the following code:
When you change the value of the age key in the previous code to a number less than or equal to 21 and refresh the page, the yellow bar is what will appear then. When the number is less than or equal to 18, only content related to children in green will appear.
You can also display personalized content based on each member’s gender, for example if the member is 20 or older and male, you will be shown personalized content. If the member is female, other content will be displayed to him. (We talked about objects previously and learned how to extract data from them.)
The previous code means that the person must be older than 18 and at the same time younger than 21. The && sign means And and requires that both conditions be met.
There is another parameter to check the occurrence of one of the two conditions, which is || It is called OR, meaning if one of the two conditions is met, the code is executed, unlike &&, in which both conditions must be met in order for the code inside it to be executed (be sure to set the appropriate logical conditions and always make sure that the signs greater than and less than are in the correct place.)
Note that the remove() function is to delete elements from the HTML page. Elements can be hidden in another way to modify the CSS, and it can be used in JavaScript as follows:
However, in our example, it is preferable to use remove() to prevent tampering with the code and show the entire content. The style.display method can be easily changed to show the entire content. The previous code is illustrative only, but if you want to hide or display any content, this must be done on the server side.
Thus, we have reached the end of the first section of the article, and we remind you here that JavaScript is a very large language and requires hundreds of pages to fully master it. But in this guide, we were keen to clarify the most important basics that qualify you to understand the language so that you can use it on your website.
In the second section, we will shed light on how to write JavaScript codes in the WordPress architecture according to best practices that will avoid problems with your site.
Using JavaScript in WordPress architecture
You may have tried many times to use JavaScript within your WordPress site files, but you failed. Maybe the code is 100% correct, but you put it in the wrong place or in the wrong way. The WordPress architecture is very flexible in modification, as it is open source and easy to use enough to do everything that comes to your mind, and in this section you will learn how to add JavaScript codes to it in the appropriate way.
You need to be careful as JavaScript codes can be easily broken or invalidated if placed in the wrong place. It may also crash the entire site if the codes conflict with each other. For example, one add-on activates a function and another add-on does the opposite of the function at the same time. So I will teach you the correct way to run any JavaScript code correctly in your site.
Where to place JavaScript code in WordPress
WordPress, like any website, contains HTML or PHP files, CSS design files, and other files for creating animation effects and creating a JavaScript interaction environment. We have previously explained that JavaScript codes are placed inside HTML files to control all site elements in two different ways:
- Directly inside the HTML file
- in an external file and then call it inside the HTML file
The same thing happens in WordPress. JavaScript codes are also added to the template ( either in the HTML pages where you want to execute the code, or in an external file and call it inside the file you want to modify).
But there is a problem that you should pay attention to, which is that if you call an element that is not on the page, this will cause an error to appear in the console and may cause some of the site’s functions to be disabled. The form of the error is as follows:
The previous error appeared because the browser searched for the element carried by the changeColor variable, but did not find it on the page. Of course, the same elements are not necessarily present on all pages of the site. For example, if you modify the phrase “Read more,” the code will work well on the main page that you are displaying, while an error will appear on the full article page because this phrase that you are trying to modify no longer exists.
Therefore, the following two notes must be followed carefully:
- Place the code only on the page whose element you want to modify. This prevents errors and prevents the code from being loaded on other pages unnecessarily.
- Use the conditional if statement to verify the existence of the element, so that you test if the element exists and then execute the code, and if it does not exist, do nothing. This way you will ensure that no unintended errors occur.
Place JavaScript code in an HTML page
Before starting, I would like to point out that JavaScript codes are best placed at the end of the page. That is, in the footer area. This ensures that all HTML elements are loaded first so that no functionality on the site is broken, and it ensures that the code finds the element because if the code searches the page before loading it, it is expected that it will not find the element because it has not been loaded yet.
Note: The JavaScript code can be placed anywhere on the page, but you must delay the execution of the code until the elements are loaded in two different ways:
The first method: Put the code under the onload event as follows:
The second method: Delay the code for several seconds (3 seconds, for example) as follows:
To place the code on the HTML page of your site in Footer, follow these steps:
- Go to your site’s control panel.
- Hover over Appearance and choose Template Editor.
- Open the functions.php file as the following image shows:
Now you need a hook in WordPress that allows you to add elements to the footer. The hook used in this case is wp_footer and is used as follows to add any elements or codes within the page:
Read more: What are hooks in WordPress and why are they important for theme and plugin developers?
After placing the previous code at the end of the functions.php file, save the file by clicking on the Update File button as the following image shows:
Now when you open the site, you will see an alert box containing the text ‘goooooooooooood’. Excellent, this is wonderful, isn’t it!
You can put any JavaScript code between the opening and closing tags of the script and it will work on your site without any problems.
Now let’s take an advanced example of using JavaScript in an HTML page .
We want to place a message that appears to the user 5 seconds after loading the site, explaining to him that he must agree to the site’s policy and that the site collects cookies from the browser to improve the user experience. So how do we do that?
Let’s think like programmers. You need to perform the following steps:
- Create an event that fires 5 seconds after the page loads, which is what setTimeout does in JavaScript.
- Create HTML elements to place the message into, and then add these elements within the page.
- Add an id or class to each element, to adjust the design of the elements with CSS so that the message appears professionally.
The following code will do the job exactly:
After adding the previous code and saving it, refresh the site and go to the end of the page to notice that the message appears 5 seconds after the site loads. But it appears messy. We’ll arrange it professionally shortly, but let’s explain the code first:
1. First we created an event that is executed after 5 seconds using setTimeout().
2. Then we created a group of variables as follows: A variable named container stores a div element using document.createElement. A variable named pElem holds the p element for paragraphs in HTML. A variable named text stores the text that will appear to the user inside it. A variable named btn contains the button that will appear to the user. , a variable named btnTxt that contains the text inside the “OK” button.
We then append each element inside its parent via appendChild, and then add a class named my-container to the parent div. Finally, we attached the parent div containing all the elements to the body element of the site.
Add CSS code to improve the appearance of the message
We need the previous message to appear smoothly from bottom to top. It is visible to the visitor. Meaning that it is in a fixed place at the end of the screen and is visible no matter how much the screen is scrolled. It does not disappear until you click the OK button.
1. From your WordPress dashboard, hover over Appearance, then Template Editor.
2. Click on the built-in css editor as the following image shows:
3. Add the following code and then click Save, as the image below shows:
4. After that, go to your site and refresh the page to appear as follows
This is amazing! is not it.
You are on your way to becoming a great WordPress developer and proficient in dealing with all files, including JavaScript files. One last thing remains, which is to hide the previous message when the user clicks the OK button. All you have to do is add JavaScript code that is executed when the OK button click event occurs.
The following code is placed at the end of the JavaScript code that we placed in the functions.php file to do the job perfectly:
Make sure you put the code in the correct place as the image below shows:
Place the JavaScript code in an external WordPress file
It is always preferable to put everything in its correct place. HTML codes should preferably be separate. It is also preferable to place your JavaScript codes in an external file away from the template files to ensure that modifications are not lost after updating.
What do you need to carry out this task? Let’s divide the work steps into small parts:
- You need to create an external JavaScript file to write the codes inside and execute them.
- You will need to upload the file into your theme.
- We need to call the file inside Html, for it to be executed.
Note: Delete the previous code (in functions.php file). Because we will put the code in our new file (be careful do not delete the CSS codes) only the codes in the functions.php file
Starting from the next line:
///Start Add JavaScript code to HTML////
Until the end of the next line:
///End Add JavaScript code to HTML////
First: Create a JavaScript file and upload it to WordPress
1. Create a file called custom-js.js. You can choose any other name, of course. Leave the file empty. We will put the codes inside it later.
2. Place the file in a folder called java-script, or any name of your choice. The file may not be placed inside a folder, but it is preferable for organization.
3- Using an FTP client program , go to the active template path and upload the file inside it, as the image below shows:
4. Go to the WordPress control panel on your site, hover your mouse on Appearance, click on Edit Templates, choose the active template, you will notice that a new folder named java-script appears, open it and open the file inside it, then add the following code inside it and save the changes as the picture shows Below:
Note that the previous code is the same as the code in the previous section, but without the php codes that enable it to work inside an HTML file. Note that after you save the file, nothing will happen and the code will not work because you need to call the file in HTML as follows:
Second: Call the JavaScript file inside the template’s HTML file
- Add the following code to the functions.php file and save the file:
In the previous code, we first created a callback function and called it add_javascript_file_to_footer. Inside this function, we used the wp_enqueue_script function to add JavaScript files from a specified path (the customjs variable is an identifier assigned to the file) to a WordPress queue.
The function get_stylesheet_directory_uri() returns the current path to the template’s layouts file (which is located in the template root directory in which our file is placed). After that, we wrote the folder name java-script and then the file name custom-js.js. We also set a version for the file so that it can be changed if we want to delete the cache for this file. The value true means placing the file in the footer. If we choose false, the file will be in the header, and this is not preferable, as we explained previously.
Finally, we used the wp_enqueue_scripts hook, which is called when JavaScript and CSS files are added inside HTML pages. This hook needs a callback function passed to it to execute when it occurs, which is add_javascript_file_to_footer in our case.
Read more: The correct way to include CSS and JavaScript files in a WordPress theme
With this, we have concluded the second section of our educational guide, and before we conclude, we would like to conclude by talking about some of the drawbacks or defects of the JavaScript language on the front end and how to overcome them.
Disadvantages of JavaScript on the front end?
The main problem or flaw of JavaScript is that when it runs on the client side, its code is always visible to everyone and anyone with average knowledge of JavaScript can easily view and manipulate the code and bypass security and verification processes on the client side easily.
For this reason, you must protect data by protecting the input fields found on the pages, and verifying that the data that the user sends using the script is safe by using a server-side language such as PHP or Node JS technology, which executes JavaScript itself on the server side or Using any other appropriate language.
But at the same time, it is preferable to install a JavaScript protection layer and verify the field inputs on the client side (making sure that the fields are not left empty, or invalid characters are used, etc.) so as not to create pressure on the server while filling out the fields. If the user tries to manipulate JavaScript codes, the second layer of protection comes in this case from the server side.
Another drawback of JavaScript is that it slows down page loading and may freeze the user interface and prevent the user from interacting with the page. Also, any error that occurs in its code can prevent the entire page from being displayed. For this reason, it is preferable to call JavaScript codes after the page elements have finished loading, using one of the methods we mentioned earlier in the article.
Conclusion
We divided this guide into two main sections. In the first section, we dealt with a simplified explanation of the basics of JavaScript, in which we explained how to declare variables, and graduated to textual, numerical, arrays and objects data types. We have provided several illustrative examples of loops and its importance in accessing all elements of arrays and objects, enabling us to implement any idea in a correct programming manner. We then graduated to the if conditional, and as a practical example we explained how to control the display of certain results according to time or according to the user’s behavior and characteristics. Finally, we explained with illustrative examples how to use functions to divide the code into blocks that can be called in any part of the code, which facilitates work and saves time and effort.
In the second section of the article, we learned about two ways to insert JavaScript codes into WordPress files and run them without causing errors that affect the site’s performance. As an illustrative example from real life, we showed how a message can be shown to the visitor after a certain time after loading the page, and how the visitor can hide this message after taking an action, which is known as Events in JavaScript. We concluded the article by clarifying some of the drawbacks of JavaScript on the website and how to overcome these drawbacks.
In conclusion, dear reader:
Although JavaScript may have some downsides, they are solvable as you have seen. This language remains the most popular and powerful language in controlling browser behavior. Therefore, we advise you to spare no effort in learning it and to try the illustrative examples that we explained in this article.
We hope that you have benefited from your knowledge of the capabilities of WordPress if properly integrated with JavaScript and applied what you have learned. Leave us your experience in the comments and tell us the difficulties you encountered while applying the examples in the article so that we can help you overcome those difficulties and advance the Arab world towards clean code.
Leave a Reply