Lessons menu
JavaScript - advanced - Lesson nr. 6
Loops and new elements from JS

What this lesson is about?
In this lesson we will learn about three things:
1.      the advantages of writing our JavaScript functions in a separate file - we will even use files/functions we did not write.
2.      creating loops, repeating instructions.
3.      adding elements to our page from JavaScript code.

New methods in this lesson:
createElement(a tagname) – this method of the document object is used to add new HTML elements to the document from the JavaScript code.

setAttribute(name of the attribute, value) – this is a method of every element object. Every HTML element is seen as object from the JavaScript code. We can set the value of an attribute. We used attributes before, they are the properties added to the tags, in the HTML code.

appendChild(an element created) – this is a method of every element object like the setAttribute method. It is used to add an element inside another one. The element referred in the parameter, is the one added to the one of whose method we use.

removechild(a reference to an element) – this method, like the appendChild can be used with every element object. The element referred as parameter will be removed from the inside of the element to which the method belongs.

Writing JavaScript codes in external files:
Using external files to store JavaScript code is useful, because the file can be referenced from different HTML files. An HTML file can use multiple JS files.
Separating script and HTML code, adds readability to our work.
The way to reference a JS file: <script src="file_name.js"> </script>

How to insert a quotation mark in JavaScript texts:
If we want to add quotation marks to texts we may face problems, because constant texts are put by default in quotations marks. We can vary simple and double marks but we may need to use \ symbols to mark the quotation marks we need to really appear in the text. This is called escape character. (Read more here: https://en.wikipedia.org/wiki/Escape_character)

Example on texts with quotations:

 


In the example above, clicking on the colored section a button appears. The HTML code for the button is constructed inside of a function.

To the quotation marks to be displayed, we added the \ symbol, the other quotation marks indicate the beginning or the end of the strings.

The result can be viewed in the browser and the code can be inspected to see the actual content. (Use right click.) Only the marked quotation marks appear.

The for loop:

If we need to repeat some instructions multiple times, we can use loops.
The for loop is mostly used, when the number of repeats is known, but it can be molded to every occasion.

The form of the for loop we will use:

for (i=1; i<=nr; i++) {
statements;
}


As we enter the loop, the index variable (not necessary to be i), get an initial value (not necessary to be 1). Afterwards, repeats the statements and checks after every repetition if the condition is true to continue, and changes the index value (with one, in the for above, but that can be changed too). If the condition gets false, the loop stops.

Example on usage of the for loop:


In the example above you find two for loops to see how they work. The CSS settings are not visible on this picture, so we concentrate on the JavaScript code.

The first loop repeats 10 times adding the value of the i variable to the content of the first section of the website. The values of the i variable are in order: 1 2 3 4 5 6 7 8 9 10.

The content of the segment is cleared, because there can be more clicks on a segment and it will fill up.

The second loop is similar to the first one, but shows us that we can complete the HTML code from JavaScript: we add ten buttons from the function and even define an alert box to be shown when clicked on these buttons.

You can see the content after evaluating the JavaScript code when inspecting the page.


The while loop:

This is another way to repeat instructions is the while loop.
Compared to the for loop, the while needs only 1 condition to decide until when to repeat the instructions, enclosed in the brackets.

The form of the while loop:

while (condition) {
         instructions;
}


If the condition is true we repeat and if we find it is false, we stop the loop.

Example on the while loop:

In the example above the first while loop has the exact same effect as our first for loop. We needed to add the initial value for the i variable and the instruction to increase it separately. The initial value is defined outside of the loop, the increasing is repeated.

The second loop, adds 10 random numbers to the second section. Each clicking on the green rectangle produces 10 new values between 1 and 101.

Example on adding/removing new sections from JS code:


In the example above, you can see how to properly add/remove new elements to/from a document. In one of the previous examples we have just “written” them (some buttons) inside of an existing element. Adding elements to the innerHTML as texts works, but it can disable event listeners working already, it is complicated to elegantly remove one of the elements or adding new one, not disturbing the ones already there.

We use the randcolor function from the 24. lesson.

The newdiv function is called when the first button is clicked on. Creates a new div element referred subsequently by the d variable. We add a value to the id property so that the div can be found later by the deldiv function. The id is unique because we use a number in it which is always increased as a new element is required.

With the appenChild method we add the div to the document, and then we add a random color as background color to see better which section is the newly added or deleted.

The deldiv function removes the last section from the document. We could remove any of them, but it is slightly complicated for a first example. The removeChild method is used to make the last div disappear.

Exercises
1. Modify the index.html file by copying JavaScript code to a separate file:
Create a new file with the name script.js in the folder of the website.
Copy every function to this file.
Include a reference to the file in the header part.
You should also remove the style tags from the head of the HTML document, and move CSS from it to the style.css file.
View the result
2. Modify the gallery.html file adding a new gallery using the JS and CSS files from the lightbox folder making the following steps:


Add a new section (ul) with the id called gallery3 and the class named pure-js-lightbox-container.

In this section you need to insert unordered list items, which should contain anchor tags, linking the image in the gallery folder. Also, these need to have inside them img tags, which link to the same image as the anchor tag. You should accomplish the making of these unordered list items with the for loop.

In the head section add a reference to the pure-js-lightbox.min.css style file from the lightbox folder, and a reference to the JS file, still from the lightbox folder.

After the for loop, create a new ligthbox object: var lightbox = new pureJSLightBox();

You should also design the gallery images as follows: 4 images on a row with some spacing between them, like the first gallery above. Also, on 700 pixels and below screen width, set the pictures to be 2 on a row.

View the result
3. Modify the first gallery in the gallery.html file, by generating the big and small images with the for loop and achieve the same result.
View the result
4. Modify the forms.html file, by adding a new part to ask some multiplying questions, using the possibility to add elements to the form from JS code. The number of questions should be determined first and then displayed by hitting a button. Make the following changes:


Create a fourth part in this page: use the <fieldset> tag  with the id section4, to delimit the section this part appears, and the legend to it should be Multiplication.

Add a range type element to determine how many questions should be asked. The number should be between 1 and 5. After this, add a din with an id, and when the range input changes, it should modify the text inside that div to show the current value of the range input, like the following example: Number of questions: 1. The number it’s the current value of the range.

Add a button, clicking on which the questions will appear. Add a function to react to the click event, name it create.

Add a form with the id form4. Add a submit button to it, and name the result function to evaluate the responses if the form is submitted. The elements will be added to this form.

The create function should create the number of textboxes shown by the range element. Every element should show two random digits with a * symbol as placeholder. Every textbox should be required to be filled and added to the form.

Also, add some design to the newly added elements.

We return to the evaluation in the next chapter using arrays.

View the result
Questionnaire
1. Choose the correct statement related to the js files!
2. What is the result of the code below?
this.innerHTML = "<p onclick=\'fct()\’ > abc\’"+"</p>";
3. How many times does the following loop repeat the instructions?
for (i=2;i<10;i++) { … }
4. What is the problem with the loop below?

i=10;
while (i>5) {
               this.innerHTML+=i+" ";
}

5. After we create an image element with the code below, how do we add a 200px width to it?
var pic=document.createElement("img");
6. Which one of the following codes is equivalent to the one below?

function fill(x){
         x.innerHTML="<p id='p1'></p>";
         document.getElementById("p1").innerHTML="Apple";
}

Exclamation mark This site is using cookies. By continuing to browse the site, you accept their use! I accept