JavaScript createElement

JavaScript createElement

In this lesson we study JavaScript createElement method, useful to create new elements in the DOM.

In the previous article we saw how to manipulate the DOM in JavaScript and studied methods for selecting elements on a page. You can consult the article at the following link: https://www.codingcreativo.it/en/javascript-dom/.

JavaScript createElement – How to create elements in the DOM

The element to create can be, for example, a new level, a new paragraph, a new title, etc.

To create elements in the DOM in JavaScript we will use the createElement() method, specifying the type of element you want to create inside the brackets.

The syntax is therefore this:

element = document.createElement(tag);

where tag can be any tag.

To add the new element, at the end of the list of elements contained in the current node, we use the appendChild() method.

JavaScript createElement – first example

So let’s see a practical example of how to create elements in the DOM with JavaScript.

If you try clicking the button below, a new item will appear.

In this point I insert the button:

For the development of this example, we first create a new layer (div) with id equal to button, which corresponds to the point where the new button will appear.

Here I will insert the button:

<div id="button">In this point I insert the button: </div>

Below we insert the button to which the onclick event is associated which calls the insert() function.

<input type="submit" onclick="insert()" value="insert">

We then create the insert() function in JavaScript.

This function will create a new button, with JavaScript createElement method, which will contain the word Scratch. Then we insert the element, using the appendChild () method, into the layer with the same id as the button.

So here’s the JavaScript code:



function insert() {
  var btn = document.createElement("button");
  btn.innerHTML = "scratch";
  document.getElementById("pulsante").appendChild(btn);
}

Conclusion

In this tutorial we have introduced the createElement JavaScript method, in the next lessons we will study other methods to manipulate the DOM.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript DOM

JavaScript DOM

In JavaScript it is possible to manipulate the DOM. In these lessons we will learn for example how to create new elements, add attributes or even delete elements in the HTML DOM.

The web browser, when it loads the web page creates the DOM (Document Object Model).

The DOM can be seen as a tree structure, such as this:

dom javascript

So, the DOM structure of this web page is therefore:

document

      head

           title

                title of the document (text node)

     body

         p

              paragraph text (text node)

        h1

              title (text node)

JavaScript DOM – How it uses

In JavaScript, by manipulating the DOM, you can add or remove existing elements and attributes, and you can also create new events on a page.

The root of the document, i.e. the web page, is represented by document. The document object is therefore the father of all other elements.

Let’s consider that you can access the elements directly, that is, without going through the entire tree.

Element is a node that represents an html element (a tag), while text is the last child node of a parent and represents a text node.

JavaScript DOM – Document methods for selecting elements on a page

We continue the tutorial JavaScript on the DOM by presenting in particular the methods of the document object to select elements.

JavaScript DOM – getElementById()

The getElementById () method identifies an element on the page through the id associated with an html tag.

So let’s take an example.

Try to click the button below, you will notice that the writing will change.

Click on the button to try getElementById.

Click on the button to try getElementById() method.

First of all, I insert a level with the div tag to which I associate the change id. Then I insert a button where I add the onclick event, to which I associate the change () function which has the purpose of changing the text contained within the div tag.

I also use the innerHTML property to change the text.

<div id="change">Click on the button to try getElementById() method.</div>
<button onclick="change()">Change</button>
<script type="text/javascript">
function change() {
  document.getElementById("change").innerHTML="Welcome on Coding Creativo";
}
</script>

JavaScript DOM – getElementsByClassName()

In JavaScript to manipulate the DOM we have another method that allows us to identify the elements of a web page based on the associated class, namely the getElementsByClassName () method.

Let’s take an example in order to understand how it works.

If we click on the button below, the last item in the list will be modified and all the elements to which the code class is associated will be given a blue background and white writing.

Scratch
Algobuild
C language
C++ language

I explain the procedure:

First of all I created a series of levels all with the same class in which I wrote the names of the programs. I want when I click the button, the last item changes and also all the layers turn light blue and the writing color turns white.

After I insert the button with the onclick event that calls the coding () function.

In JavaScript then I construct this function in such a way as to take the element with index 3 to which the code class is assigned and in place of the previous content it replaces the Java text.

In addition to all the elements of class code, as mentioned before, I change formatting.

I attach the JavaScript and html code:

<div class="code">Scratch</div>
<div class="code">Algobuild</div>
<div class="code">C language</div>
<div class="code">C++ language</div>

<button onclick="coding()">Change</button>

<script>
function coding() {
  document.getElementsByClassName("code")[3].innerHTML = "Java";

var list = document.getElementsByClassName("code");
for (var i = 0; i < list.length; i++) {
  list[i].style.backgroundColor = "#f67f92";
  list[i].style.color = "#fffff";
} 
}
</script>

JavaScript DOM - getElementsByTagName()

We continue the JavaScript dom tutorial by introducing another method for selecting elements, the getElementsByTagName () method.

This method allows you to identify the elements of a web page by the name of the tag.

Let's take an example now.

If we click the change button, a blue background will be set for all the writing, except for the text outside the div.

Scratch

Text outside the div....

Algobuild
C language
C++ language
Click on the button to try getElementsByClassName().

To create this example, first of all we insert a main level to which we assign an id codingC and inside we will insert other levels and a paragraph.

As mentioned before, we want to give all divs the same formatting, while the paragraph must keep the original formatting.

So in JavaScript I create a coding () function that takes the list of the elements of div that are inside the tag with id equal to codingC and assigns them a custom background.

<div id="codingC">
  <div class="code">Scratch</div>
  <p> Text outside the div....</p>
  <div class="code">Algobuild</div>
  <div class="code">C Language</div>
  <div class="code">C++ Language</div>
</div>

<div id="cambio">Click on the button to try getElementsByClassName().<div>

<button onclick="coding()">Change</button>

<script type="text/javascript">
function coding() {

var el= document.getElementById("codingC");
var list = el.getElementsByTagName("div");
for (var i = 0; i < list.length; i++) {
  list[i].style.backgroundColor = "#a5cff3";
} 
}
</script>

If we wanted to include the paragraph as well, we would just have to change this line of code:

var list = el.getElementsByTagName ("div");

and then indicate

var list = el.getElementsByTagName ("*");

where the asterisk indicates all elements.

Conclusion

This article is just a small introduction to DOM in JavaScript, we will continue in the next tutorial to explore other methods and events.

Finally we point out the w3schools website for the JavaScript DOM: https://www.w3schools.com/js/js_htmldom_events.asp.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

callbacks in JavaScript

callbacks in JavaScript

In this lesson I propose some examples of the use of callbacks in JavaScript.

I have already covered these callback functions in the following articles:

  1. JavaScript functions and return
  2. JavaScript Callback
  3. Callbacks
  4. Array method and callback functions

callbacks in JavaScript – examples

We create functions for calculating the area of ​​the rectangle and the area of ​​the triangle. Both functions return a return value that corresponds to the area of ​​our geometric figure.

Then we create a new area function to which we will pass two arguments representing the base and height of our geometric figures and a third argument which is our callback function. The function must be passed without round brackets, as we have said several times in previous lessons.

This function returns the same callback function called on the two parameters x and y.

We call up the area function once to calculate the area of ​​the rectangle, another time to calculate the area of ​​the triangle.

First we make the example with constant values, then we will insert them via a simple prompt.

Below is the complete code for our first example on callback functions:



alert('The area of ​​the rectangle is ' + area(5, 15, areaRect));
// calls the function area with 3 arguments of which the last is the callback function
alert('The area of ​​the triangle is ' + area(5, 15, areaTriangle));

var num1 = parseInt(prompt('Insert number 1'));
var num2 = parseInt(prompt('Insert number 2'));
alert('The area of ​​the rectangle is  ' + area(num1, num2, areaRect));
alert('The area of ​​the triangle is  ' + area(num1, num2, areaTriangle));

//**** functions ****//
function area(x, y, callback) {
    return callback(x, y);
}

function areaRect(a,b) {
  return a * b;
}

function areaTriangle(a,b){
    return a * b / 2;
}

callbacks in JavaScript – second example

In this second example we use a simple greeting function which is used to display the greeting via an alert.

Next we create a dataIntput function that takes a callback function as an argument. This function will ask to take data as input which will then pass to the same callback function.

We then call our dataInput function to which we will pass the greeting function as an argument.

This example is very convenient especially if we need to modify the alert with a console.log or a getElementById, for example. This way I don’t touch the main function but just change the greeting function to show a different type of output.



dataIntput(greeting);

function greeting(name, lastname) {
  alert('Welcome ' + name + ' ' + lastname);
}

function dataIntput(callback) {
  var n = prompt('Insert name');
  var c = prompt('Insert lastname);
  callback(n,c);
}

Conclusion

In this lesson I have proposed some examples on callbacks in JavaScript, I will return soon to propose many other exercises.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript setTimeout

JavaScript setTimeout

JavaScript setTimeout is a method that allows you to call a function after a certain period of time, expressed in milliseconds.

The syntax of this method is: setTimeout(function, milliseconds, p1, p2, …).

Both milliseconds and p1 and p2 are optional parameters.

The mandatory function will be executed after the time indicated in milliseconds has elapsed, otherwise after 0 seconds, if this parameter is not specified. Therefore 0 is the default value.

JavaScript is not multi-threaded but single-threaded, meaning it can only execute one task at a time at any given time.

The JavaScript engine then executes the code from top to bottom, therefore it is said to be synchronous. Through callbacks, promises and methods such as setTimeout, JavaScript performs asynchronous activities.

In addition to the JavaScript engine, the web browser also has Event Loops, Call Stacks and Web API as components.

When we use setTimeout, the JavaScript engine inserts the execution context it creates into the Call Stack. This creates a timer in the Web API component of our web browser. When time elapses, the callback function, passed as an argument to the setTimeout method, is placed in a queue.

The event loop checks both the stack and the queue, removes the callback function from the queue, puts it on the stack and then the function is executed.

JavaScript setTimeout – first example

We realize two functions quote and other quote.

The first is a function that contains the setTimeout method which has as its first parameter a callback function that simply activates an alert with a famous quote from the movie “The Imitation Game“. The second parameter instead represents the time in milliseconds. Then the function, when called, will start after 2 seconds.

The second function, on the other hand, is a function that contains another alert with another quote, different from the previous one and which has no time limit.

Here, then, is the complete code for using the setTimeout method in JavaScript:



quote();
otherQuote();

function quote() {
  // start after 2 seconds
  setTimeout (function () {
    alert('They are the people that no one imagines that they can do certain things those who do things that no one can imagine!');
  }, 2000);
}

function otherQuote() {
  alert('People never say what they mean, they always say something else. Yet they expect you to understand them ...');
}

Even if the quote function is called first, the otherCitation function will start first as it has no time restrictions.

setTimeout JavaScript and clearTimeout

Let’s create a simple count that we will stop with the clearTimeout method.

Then, let’s prepare our HTML page with this simple code:

  <div id="container">Inizio conteggio:
    <span id="conta"></span>
    <button id="stop" class="btn">stop</button>
  </div>

So I use a span where I’m going to put the progressive numbers and a button to stop everything.

Then I program my algorithm in JavaScript.

We initialize the count variable to 0 and save the timer created in a variable named myTimer.

Inside the callback function we will increment the count variable and then recursively call the setTimeout method to produce the next increments. Let’s give the time of 1 second.

When we click the stop button we call the stopCount function which will call the clearTimeout method on the myTimer variable.

Here is the complete code that uses the JavaScript setTimeout and clearTimeout methods:



var count = 0;
var myTimer = setTimeout(function timer() {
  document.getElementById("count").innerHTML = ++count;
  myTimer = setTimeout(timer, 1000);
}, 1000);

var stop = document.getElementById('stop');
    stop.addEventListener('click',function (){
    stopCount();
});

function stopCount() {
    clearTimeout(myTimer );
}

Conclusion

In this lesson we speak about setTimeout and clearTimeout in JavaScript, in the next lesson we will talk about timers again using the setInterval method.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

functions in JavaScript

functions in JavaScript

In this lesson we will delve into the functions in JavaScript, already introduced in the previous lesson. The lesson can be consulted at the following link: introduction to functions.

functions in JavaScript – examples

In particular, in this example I propose a demonstration of how it is possible to use multiple returns. So let’s create a function named isPositivo and return a value depending on the result of our conditional statement contained within the function.

We therefore pass a number a as a parameter. After, if the number is positive, the function returns 1, if it is null it returns 0, otherwise if it is negative it returns -1.

This is an example of functions in JavaScript:



function isPositive (a) {
  if (a> 0) {
    return 1;
  }
  else if (a == 0) {
    return 0;
  }
  else {
    return -1
  }
}

So we call the function, passing as a parameter, for example, the number -6. We store the return value in a variable named result. Finally we print the result obtained in the console.log().



var result = isPositive(-6);
console.log(result);

In this case we display the value -1 in our console.

Of course, you can return any value, even a string.

So, this is another example of using functions in JavaScript:



function isPositive(a){
  if (a > 0){
    return 'Positive';
  }
  else if (a == 0){
    return 'Null';
  }
  else {
    return 'Negative';
  }
}

var result = isPositive(-6);
console.log(result);

The same function could be written using a variable that for example I set to an initial value. Then only if certain conditions occur I change the value.

Here is a possible change to the previous function, using a string:



function isPositive(a){
  var result = 'Negative';
  if (a > 0){
    result = 'Positive';
  }
  else if (a == 0){
    result = 'Null';
  }
 return result ;
}

var result = isPositive(-6);
console.log(result);

So I change the value of the variable only if the number is positive or null.

Note that the variable result contained within the function is not visible externally. In fact it is a local variable of the isPositivo function. So I can use the same name to store the return value from the function.

Conclusion

In this lesson we have developed a simple example of a function with the possibility of handling different returns, in the next lessons we will talk more about functions in JavaScript.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

callback functions

callback functions

The callback functions are used in JavaScript to ensure that the code is asynchronous, i.e. executed after a certain event, such as when a button is clicked, or when you pass over an element of the html page, etc.

We have also seen in previous articles that callback functions can be passed as arguments to functions, as they are objects.

In this article we will give some more examples to better understand their use.

In fact, their use with other predefined methods is interesting, as in the first example below.

callback functions – first example

We remove the odd elements from a previously populated array.

First let’s create our array of numbers.

Next we create an anonymous function in JavaScript which we store in a variable number.

So in the variable number we are storing our callback function, which represents our object.

Then we filter the array using the filter method which invokes our callback function in Javascript, which was created to return true if an element is even.

The callback function takes a single parameter that represents each single element of the array that must be evaluated.

Then the function is called without round brackets within the filter method.



var array = [5,7,8,9,10];

var number = function(n) {
  if(n % 2 == 0){
    return true;
  }
};

//number becomes the function that I can call, therefore:
var num = array.filter(number);
console.log(num);

The console.log will print the array with only even numbers.

Therefore, the same function can also be written like this:



var array = [5,7,8,9,10];

var n = array.filter(function (n) {
  if(n% 2 == 0){
    return true;
  }
});

console.log(n);

callback functions – second example

We insert 5 numbers in an array at the click of the button and then display their sum.

Also in this case we use an anonymous callback function within which we call the functions askNumbers and sumNumbers.

The AskNumbers function takes an array and the quantity of numbers to insert as arguments, while the AddNumbers function takes the array as an argument.



var numbers = [];

var calculation = document.getElementById('calculation');

calculation.addEventListener('click',function (){
  insertNumbers(numbers, 5);
  var sum = sumNumbers(numbers);
  alert('Sum is: ', sum);
});


function insertNumbers(arr, q){
  while (arr.length < q){
    var n = parseInt(prompt('Insert a number));
    arr.push(n);
  }
  return arr;
}

function sumNumbers(array){
  var sum = 0;
  for (var i = 0; i< array.length; i++){
    sum += array[i];
  }
  return sum;
}

Conclusion

We have done some exercises on callback functions in JavaScript, in the next lessons we will return to this topic.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

callbacks

callbacks

Callbacks in JavaScript, as seen in the previous lesson, can be passed as arguments to other functions.

In fact, functions in JavaScript are objects. We can also see this simply by doing the console.log of a function.

For example, if we have this JavaScript function:



var number = function(item) {
  return 10;
};

console.log(number);

If you do the console.log() of the variable number we will see that it is an object, as shown in the following figure:

funzione oggetto

Callback functions can be anonymous or have a name. The obvious advantage of having a name is that they can be called up in other portions of code, as well as making the code more readable.

Why are callbacks in JavaScript useful?

As we know JavaScript executes the code sequentially, and sometimes we need to execute the code after something else occurs. That is, we need to do something asynchronous!

Callback functions allow you to execute code only after completing certain actions. They are then recalled after completing an activity.

callbacks – examples

Let’s take another simple example of a callback function used to calculate the area of ​​the rectangle at the click of a button.

If we have a button with a calculation id on the HTML side:

<button id="calculation" class="btn">Calculation</button>

In JavaScript we program the areaRect callback function.

Here is the complete code with callbacks:



var calculation = document.getElementById('calculation');

calculation.addEventListener('click',areaRect);

function areaRect(a,b){
  a = parseInt(prompt('Enter the base value: '));
  b = parseInt(prompt('Enter the height value: '));
  alert(a*b);
}

So only after clicking on the button will the areaRect function start, which therefore waits for the click to finish.

Try not to release the mouse button right away.

Notice how, after the areaRect callback function, there are no round brackets.

Let’s make a small variation of the previous example, in order to create an additional function for printing the area of ​​the rectangle.

So the areaRect function will only return the calculation of the area. While the printArea function, which has as its argument only the areaRect function, will print the result.

Here is the complete code that shows the use of callbacks:



var calculation = document.getElementById('calculation');

calculation.addEventListener('click',printArea);

function areaRect(a,b){
  return a*b;
}

function printArea(){
  let base = parseInt(prompt('Enter the base value: '));
  let height = parseInt(prompt('Enter the height value: '));
  printResult = areaRect(base,altezza);
  alert(printResult);
}

The above code can also be written via an anonymous callback function in JavaScript:



var calculation = document.getElementById('calculation');

calculation.addEventListener('click',function (){
  let base = parseInt(prompt('Enter the base value: '));
  let height = parseInt(prompt('Enter the height value: '));
  printResult = areaRect(base,height);
  alert(printResult);
});

function areaRect(a,b){
  return a*b;
}

Conclusion

In this lesson we explored callbacks in JavaScript we will continue to talk about them in the next article.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript callback

JavaScript callback

In this lesson we will talk about JavaScript callback functions, which are functions that are passed as parameters to other functions.

In the JavaScript version ES5 they are widely used, while in the ES6 they leave room for the promises that have become a native component of the language. A few years ago, in fact, the promises were used only thanks to external libraries.

Callback functions derive from a programming paradigm known as functional programming.

It is also good to remember that when we pass a callback function as an argument to another function, we are not executing the function, but we are only passing the definition of the function. So we don’t have to use round brackets, as we do when we execute a function instead.

JavaScript callback – first example

In this first example we will use a simple function for the sum of two numbers and then we will pass it as a parameter to another function.

So here is the code of our function which simply takes 2 numbers and returns their sum:



function sum(a,b){
  return a + b;
}

The function to which we will pass our function as an argument, therefore without brackets we will call it callsCallBack simply to make it clear that it calls a callback function.



function callsCallBack(callback){

  var number1 = parseInt(prompt('Insert a first number '));
  var number2 = parseInt(prompt('Insert a second number '));

  alert(callback(number1,number2));

}

Now let’s call the function:



callsCallBack(sum);

If you try the script you will notice that an alert will appear where the sum of the two numbers taken as input will be visible. If you prefer, use the console.log()!

JavaScript callback – second example

In this second example we will create an evenOdd function that returns true if a value passed as an argument is even, otherwise it returns false.

After our function callsCallBack we will pass a number and the function just created as arguments, without brackets. If the number passed is even we will print the string ‘even number’, otherwise we will print ‘odd number’.



function evenOdd(item) { 
  //function which will then be passed as an argument without brackets
  if (item % 2 == 0){
    return true;
  } else {
    return false;
  }
}

function callsCallBack(x,callback){ 
    //the parameters are a number and a function
    if (callback(x)) {
      console.log('even');
    } else {
      console.log('odd');
    }
    return x;
}


for (var i = 0; i < 10; i++){
  var n = parseInt(prompt('insert a positive number'));
  var y = callsCallBack(n,evenOdd);//I call the function without brackets
  console.log(y);
}

JavaScript callback – third example

In this third example we will populate an array of only numbers greater than or equal to zero (we discard only the negatives), again using the callback functions.

Then we create our positiveNegative function which returns a Boolean value.
Then we create the myArray function to which we pass a number, an array and a function as an argument (so I remind you without brackets), and we add the element to the array only if it is positive. This function returns our array.

Finally, through a for loop we ask for a number and call the popolaArray function with our parameters.

If we do the console.log() we can see our array populated with only numbers greater than or equal to zero.



function isPositive(item) { 
  if (item >= 0){
    return true;
  } else {
    return false;
  }
}

function myArray(x,array,callback){ 
    //where the parameters are a number, an array and a function
    if (callback(x)) {
      console.log('positive number - put it in the array');
      array.push(x);
    } else {
      console.log('negative number - don't put it in the array');
    }
    return array;
}

var numbers = [];

for (var i = 0; i< 10; i++){
  var n = parseInt(prompt('insert an integer number'));
  var y = myArray(n,numeri,isPositive);
  //I call the function without brackets
  console.log(y);
}
console.log('array: ' , numbers);

Conclusion

In this article we have seen some simple examples of using JavaScript callback functions, in the next lessons I will propose many other practical examples.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

format JSON

format JSON

format JSON – JSON is a format used for data exchange and is the acronym for JavaScript Object Notation.

It is based on the JavaScript language and is used a lot for asynchronous programming, therefore with ajax, as we will see in the next lessons.

JSON is a text format, so it is a string. It allows you to aggregate data and follows the syntax of JavaScript objects.

But it can be used independently of JavaScript, in fact many programming languages ​​use it and therefore also allow you to do the parse.

A JSON object is created using a pair of curly brackets that are used to contain the whole object. Then, inside these brackets, the various properties are inserted indicating key-value pairs and making sure to use double quotes for both the key and the value. Each property of the object is separated by a comma.

format JSON – example

Let’s take some examples of JSON objects.

This is an example of JSON format:



{
  "type":"Fiat",
  "model":"500",
  "color":"white",
  "powerSupply":"gas",
  "year":"2010"   
}

The json data is described as key-value pairs, in this example we have an auto object with some property, as for example: tyoe, model, color, ecc.

The JSON object can be even more complex, as for example this API:

format JSON e JavaScript

A JavaScript object is very similar to a JSON.

Let’s take an example of using JSON with JavaScript. So let’s take our usual auto object and write it as a JSON object, remembering that it’s a string.

Since it is a string we can use the simple superscript or the double superscript, without going to a new line. Or you can use the backtick (`) that is the back-to-back apex. To obtain the back-to-back apex, just hold down the ALT key and at the same time the numbers 0096 on the numeric keypad.

So let’s see a JSON object written using backticks:



var car = `{
  "type":"Fiat",
  "model":"500",
  "color":"white",
  "powerSupply":"gas",
  "year":"2010"   
}`;

and without:



var car = '{
   "type":"Fiat",
   "model":"500",
   "color":"bianco",
   "powerSupply":"gas",
   "year":"2010"
}';

Or alternatively, you can join the strings with the + operator, as shown in the example below:



var car = '{'
  + '"type":"Fiat",'
  + '"model":"500",'
  + '"color":"white",'
  + '"powerSupply":"gas",'
  + '"year":"2010"'+
'}';

If we try to do the console.log we will notice that what we have written is not an object but a string.



console.log(car);

In the next lesson we will see how to parse the following code in order to convert it into a JavaScript object.

For more information on the format JSON, you can consult the reference site: http://json.org/example.html.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

prompt JavaScript

prompt JavaScript

In this article we will talk about prompt in JavaScript, that is, windows that require a user to enter data.

The prompt () method therefore allows you to bring up windows to interact with the user.

prompt JavaScript – example 1

We want to make this example: when we click on the enter name button, the dialog box to enter the name will appear. After entering it and clicking ok, the greeting followed by the name just entered will appear in the level below.

Then try the example by clicking the button.

We then insert a button, anywhere on the page, which when clicked will bring up the dialog box for entering the name.

<button onclick=”myName()”>Insert the name</button>

In the div, which you can enter for example under button, I display the name that the user entered.

Let’s insert the JavaScript code now.

The JavaScript prompt () method has two arguments: the first that asks you to enter the name and the second that already appears in the field when the window opens (pre-filled value).

If the variable name is equal to the empty string then we display the message: ‘you have not entered the name’; otherwise we display the greeting followed by the name.

We are also using the getElementById () method which we will explore in the next articles.


function myName() {
   var messagge;
   var name = prompt("Insert your name:", "Coding Creativo");
   if (name == null || name == "")
      messagge = "You don't insert the name";
   else
     messagge = "Hi " + name;
   document.getElementById("view").innerHTML = messagge;
}

prompt JavaScript – example 2

Let’s take another simple example now, using the prompt () method. For example, we calculate the age of a person after requesting entry through the dialog box.

We insert the button anywhere on our page.

<button onclick="myAge()">Age Calculator</button>

Then we build our script, using the prompt () method to get the user's birth year to be entered.

We then get the date of the day with the Date () object and store it in the myData variable. Then we use the getFullYear () method to get the current year from the myData and store it in a variable named myYear.

So, to get the age we simply make a difference between the current year and the year the user entered.

Here is the complete script that uses JavaScript prompt:


function myAge() {
   var year = prompt("In what year were you born?", "1990");
   if (year !== null) {
         var myData = new Date();
         var myYear = myData.getFullYear();
         var age = (myYear - year);
         if (age < 18)
               alert("You are a minor, you have " + age + "years");
         else
             alert("You are of age, you have " + age + "years");
    }
}

Of course these are just simple examples of using the prompt () method in JavaScript.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts