Avançar para o conteúdo principal

Nova aplicação - Programação em JavaScript

Deixo aqui o texto da aplicação para iniciação à linguagem de programação JavaScript.

Programming in JavaScript Part One

-------------------------------------------------------------------------

Programming in JS – Part One

Introduction

What is JavaScript?

JS or JavaScript is described as the programming language for the web. It generally runs on a web browser (like Chrome, Mozilla; etc). It is a scripting language build to implement things in web pages. Therefore, it does not “make” an executable file. It runs a program or some instructions by an interpreter by a built-in interpreter (in the web browser) it is not compiled.
It´s not similar to Java!
Simplifying – Is a programming language that runs over a web browser. It allows to make changes and operations on a web page, but also make calculations, etc. And nowadays you can make a Mobile or Desktop App.

First, take notice of some conventions used in this course:
File names - index.html
Text to type -

All the code was tested, if don´t work with you, please check the upper and lower cases, signs, etc.

Setup

Preparing your environment.

JavaScript as said before runs over a web browser (not always, but assume as truth by now). So, we need to prepare some files to run a JavaScript code on a web browser.
First we should learn that JavaScript is the part of the Front End pack. The Front End is the part of a Web Page (lets assume like that to simplify it) that the user can see and interact. Some “backstage” operations (on a server, a search on a server or database) are the called Back End.
The files we need to prepare are related to the Front End. In general, it contains three files:
  • HTML file(s), is what you see in screen, like a document.
  • CSS file, is a file(s) that can colour, fancy, text fonts, etc.
  • JS, is the JavaScript file(s) that, for example respond to a button, make some calculations or animations.
In this course, we will use the HTML (so we can visualize something, as a user interface) and the JS.

The HTML file, is a plain text file, like the CSS and the JS. Can be created and edited in the simplest text editor or an advanced one that helps the user, suggesting words, formatting text and check for errors.
The HTML is an acronym for Hyper Text Markup Language. Currently in version 5, so we see often HTML5.
The CSS is Cascade Sheet Styles, and JS is the JavaScript.
The HTML file, have some fields or blocks, that are grouped in some keywords, called Marks or Tags, so its a Markup Language. A simple one is the Header represented by “h1” - A text header of size/hierarchy 1. One tag opens the field where you write the header and other closes it.
Check the

and the

.

Build you HTML.
You can type the following in a text editor (if in windows use, for example the Notepad):

Heading

Text.
Save the file as index1.html
Be sure that if in windows, you don´t have the filename extensions hidden, or you can save the file like index1.html.txt without knowing. it needs to be an html extension.
Now, double click it (or open in your web browser), and it runs in your web browser. You should see something like the following image:




To edit it, open it as said before in a text editor.

Coding

Write your first program.

As said before, the JavaScript can be located in one separated file, is one of the three kind of files, HTML CSS and JS. But if it´s a really simple program, like ours, it can be included in the HTML itself. By now lets include it in the HTML.
In the HTML we need to put the JS instructions in a separete “space”.

Now type in the following code and save it as index2.html
 
 

Heading

 
id="demo"
>Text.
 
Notice the code is indented, have spaces to match the columns of the same hierarchy, it simplifies the lecture.
And we introduced the field for the script – The JavaScript, inside the tags , we also put an identifier in the paragraph tag, its is used to identify the text “Text” with a name that the program can search and modify, later with the instructions document.getElementByID(“demo”).innerHTML, and please respect the uppercases.
Well by now accept the instruction on the left sign of =, is a way to the program can output our instructions, the other way is seeing the results in a console inside the web browser (if in Chrome press CTRL+SHIFT+I) but we will not use it by now.

Now, double click it, and it runs in your web browser. You should see something like the following image:


What happened? Well your JavaScript code, substitute the original text for another phrase.

Coding

Write your second program.

Now, with the same base code, let´s change it to make a simple calculation and present the result.
Now type in the following code and save it as index3.html


Sum two numbers


Text.
 

What happened? We change the header to match what kind of operation we are doing, a sum. And put some code to calculate the sum of two numbers.
Notice that we declare a variable a and b, and assign in that moment an value, or in case of the variable c it is not declared before, it receives the sum of a and b, and also its type, an integer.
Now, double click it, and it runs in your web browser. You should see something like the following image:

Now, maintaining the base structure of this file, you can explore it, make changes and go further.

Coding

Write your third program – Functions.

A function can be seen as a set of instructions, you can enter an input and it gives you the result of some calculations. It can vary, but by now lets stay with this idea.
So lets make the same calculation, the sum of two numbers, but using a function.
Now type in the following code and save it as index4.html
 
 

Function - Sum two numbers

 
Text.
 
 
We change the header to describe what kind of operation we are doing a Function.
Now, very important, a function is a function in JS if written like it is, in lower case (remember to respect upper and lower cases). The name of the functions can be almost anything, in our example we gave a descriptive name of what it does SumTwoNumbers. Next is the input value(s) separated by commas. Next is the code of the function inside curly brackets {}. Is best practice separate these parts to better lecture.
The return statement tells the function that the output is the calculated c value.
Inside the function we used the same code of the previous example. But now the result c is the output of the function and as input the program assumes the values entered by the function. When terminated the function the calculations are done, but is not written anywhere, so we put it in our already used “demo” id. We put in a single step the name of the function and the inputs, and the result will be written in our “demo” id text.
The output in the web browser is the same that one before apply the function.

Separate files

Use JavaScript in separate file.

Now lets try to separate the JS file, as usual practice, like it was before told. Usually we have three separate files to build a interactive web page, or app. The most usual three files are the HTML, CSS and JS, see previous chapters,working together, can produce a rich webpage.
Now type in the following code and save it as index5.html
 
  Programming in JS
 
 
   

Function - Sum two numbers

   
Text.
   
 
Now we put a new tag, the and introduce the tag that gives a name to the window of the web browser.
Also, we put a script tag almost at the end, that is the necessary to contain a link, a way to inform the web page that we have an external JS file, that is included when this run.
From the script tag, the most important is the filename function.js that is inside a sub folder where the file index5.html exists (as a good practice) be careful is a forward slash / !
Now in the sum.js file put the code of the function that we used before, between the script tag:
function SumTwoNumbers(a,b){
  c=a+b;
  return c
  }
document.getElementById("demo").innerHTML = SumTwoNumbers(11,23);
And the result should be the same as before.

You can use your function a thousand times in the code, only is written once in the file.

End of part one

Please, practice the previous exercises. Be familiar with Web Browsers, file manager, Notepad, etc.
Try to change values or texts. Analyze the code.
Any suggestion or error, please write to jose.coimbras@gmail.com

Try soon the second part of this series.
Thanks, and please click the Advertising to support the author.  

Comentários

Mensagens populares deste blogue

C# - Viadutos Excel - ISPOL

C# - Viadutos Excel - ISPOL Ler dados do Excel e passar a informação para o ISPOL é um ganho de produtividade e organização. Desta vez, apresento uma utilidade que lê um ficheiro Excel, e transforma os dados para o menu de estruturas do ISPOL. Partindo de um Excel organizado, por pks eixos e espessuras da estrutura etc... como o seguinte: Elaborei um programita em CSharp: Este programa funciona em modo "DOS" não tem uma interface gráfica de janelas: O programa cria os ficheiros necessários, o Excel pode estar organizado por eixos, e o programa guarda um ficheiro para cada eixo: O resultado depois de abrir o ficheiro em ISPOL é o seguinte: Com as alterações ao projecto pode-se manter um ficheiro de apresentação e controlo em Excel.

Politica de privacidade das aplicações colocadas na Play Store do Google

Politica de privacidade das aplicações colocadas na Play Store do Google. As aplicações não recolhem qualquer dado do utilizador nem a armazenam ou partilham com terceiros. Não recolhem a localização nem a armazenam ou partilham com terceiros. Alguma informação sobre os utilizadores que possa chegar ao programador por via da Play Store, será tratada de acordo com toda a confidencialidade, e não fornecida a terceiros. Obrigado.

ISPOL - Areas de linhas fechadas CAD + ISTRAM

ISPOL - Areas de linhas fechadas CAD + ISTRAM Por vezes em CAD deparamos com alguns problemas em determinar as áreas de linhas que aparentemente estão fechadas ou contíguas, mas na verdade não estão. Mostro a introdução do ISTRAM num fluxo de trabalho de medição de áreas em CAD. Vista 3D do exemplo Como se mostra na primeira imagem, gerei uma rotunda de forma rápida em ISPOL. Em CAD, suponhamos que queremos medir as áreas em planta de pavimentos, passeios... Depois de uma limpeza e algum tratamento ao picar na área que aparentemente está fechada, que poderia representar a berma ou um passeio, temos um aviso comum no CAD, as linhas não têm continuidade. Neste caso em mais de uma situação, e na figura, apenas para a "área inferior". Linhas em CAD Podemos introduzir no fluxo de trabalho o ISTRAM, se a ele tivermos acesso. Podemos fazer um copy paste directo (linhas) do CAD para o ISTRAM. As mesmas linhas em ISTRAM Um primeiro passo pode ser filtrar e tratar o desenho, unindo de