Difference between revisions of "JavaScript"

From Sinfronteras
Jump to: navigation, search
Line 1: Line 1:
* Javascript runs on the client side in the browser.
+
https://www.w3schools.com/js/default.asp
* Javascript code is interpreted by the browser.
 
* In JavaScript, instructions are called statements and are separated by a semicolon (;).
 
  
 +
JavaScript and Java are completely different languages, both in concept and design.
  
<br />
+
JavaScript is one of the 3 languages all web developers must learn:
==Script tag in a html file==
+
# HTML to define the content of web pages
* <script> tag allows us to include a piece of Javascript in a HTML document:
+
# CSS to specify the layout of web pages
<syntaxhighlight lang="php">
+
# JavaScript to program the behavior of web pages
<h1>Testing alert</h1>
 
<script>alert("hello!");</script>
 
</syntaxhighlight>
 
  
* Including large programs directly in HTML documents is often impractical. The <script> tag can be given an src attribute in order to fetch a script file (a text file containing a JavaScript program) from a URL.
+
Web pages are not the only place where JavaScript is used. Many desktop and server programs use JavaScript. Node.js is the best known. Some databases, like MongoDB and CouchDB, also use JavaScript as their programming language.
<syntaxhighlight lang="php">
 
<h1>Testing alert</h1>
 
<script src="js/myfile.js"></script>
 
</syntaxhighlight>
 
  
* '''Variables:'''
 
** JavaScript is case-sensitive username and userName are different.
 
** JavaScript is a dynamically typed language. You don't have to specify the datatype of a variable when you declare it.
 
** Data types are converted automatically as needed during script execution. So, for example, you could define a variable as follows:
 
:: '''var answer = 42;'''
 
:: And later, you could assign the same variable a string value, for example:
 
:: '''answer = "Thanks for all the fish...";'''
 
:* A variable declared using the var statement with no initial value specified has the value '''undefined'''.
 
:** An attempt to access an undeclared variable will result in a ReferenceError exception being thrown:
 
:*** You can use '''undefined''' to determine whether a variable has a value. In the following code, the variable input is not assigned a value, and the if statement evaluates to true:
 
  
<syntaxhighlight lang="php">
+
<br />
var input;
+
==What JavaScript can do==
if(input === undefined){
+
What JavaScript can do / What is used for / some of the most important methods:
    doThis();
+
* JavaScript Can Change HTML Content
}else{
+
* JavaScript Can Change HTML Attribute Values
    doThat();
+
* JavaScript Can Change HTML Styles (CSS)
}
+
* JavaScript Can Hide HTML Elements
</syntaxhighlight>
+
* JavaScript Can Show HTML Elements
  
* '''Type coercion:'''
 
** Depending on the type of operation javascript will attempt to coerce a variable into the correct type. For example, consider the following statements:
 
<syntaxhighlight lang="javaScript">
 
x = "The answer is " + 42 // "The answer is 42"
 
y = 42 + " is the answer" // "42 is the answer"
 
</syntaxhighlight>
 
:* In statements involving other operators, JavaScript doesn't convert numeric values to strings. For example:
 
<syntaxhighlight lang="javaScript">
 
"37" - 7 // 30
 
"37" + 7 // "377"
 
</syntaxhighlight>
 
  
* '''Javascript Strings:'''
+
<br />
** The + operator can be used to concatenates strings:
+
==Installation==
** The following line will produce the string "concatenate":
 
<syntaxhighlight lang="javaScript">
 
"con"+"cat"+"e"+"nate"
 
</syntaxhighlight>
 
  
* To output debug statements (on the Terminal) the '''console.log()''' function is used, similar to '''echo''' in php:
 
<syntaxhighlight lang="javaScript">
 
var = 10;
 
for (var i=0 ; i<10 ; i++){
 
    console.log("Loop value: "+i);
 
}
 
</syntaxhighlight>
 
  
* '''Javascript Arrays:'''
+
<br />
** JavaScript provides a data type specifically for storing sequences of values. It is called an '''array'''. The
+
==IDE for JavaScript==
<syntaxhighlight lang="javaScript">
 
var myArray = [];  //empty array
 
  
var listOfNumbers = [2, 3, 5, 7, 11];
 
console.log(listOfNumbers[1]);
 
console.log(listOfNumbers.length)
 
</syntaxhighlight>
 
  
:* We can determine the length (or number of elements) of an array using the '''.length property'''
+
<br />
<syntaxhighlight lang="javaScript">
+
==Control flow statements==
console.log(listOfNumbers.length)
 
</syntaxhighlight>
 
  
:* '''Array iteration:'''
 
<syntaxhighlight lang="javaScript">
 
var myArray = ['none','two','three','four','five','six'];
 
for (var num in myArray){
 
    console.log(myArray[num]);
 
}
 
</syntaxhighlight>
 
  
:* '''indexOf'''
+
<br />
<syntaxhighlight lang="javaScript">
+
===If statements===
var myArray = ['one','two','three','four','five','six'];
 
myArray.indexOf('two');  // 1
 
</syntaxhighlight>
 
  
* Functions in Javascript come in many forms. But predominantly we can have:
 
** named, or
 
** anonymous functions.
 
  
:* A named function looks something like this:
+
<br />
<syntaxhighlight lang="javaScript">
+
===For Loops===
// Define a function
 
function myFunction() {
 
    console.log("function called");
 
    // do something interesting
 
}
 
  
myFunction(); //execute the function
 
</syntaxhighlight>
 
  
:* An anonymous function is a function without a name. It is generally assigned as a variable value:
+
<br />
<syntaxhighlight lang="javaScript">
+
===While Loops===
var func = function(){
 
    console.log("Anonymous function executed...");
 
}
 
  
func();  //Execute the function
 
</syntaxhighlight>
 
  
:* All functions can accept parameters and can use the '''return''' keyword:
+
<br />
<syntaxhighlight lang="javaScript">
+
==Methods==
function myFunction(var1, var2, var3){
 
    newValue = var1 + var2;
 
    console.log(newValue + var3);
 
}
 
  
var returnValue = myFunction(12, 13, 30);
 
console.log(returnValue);
 
</syntaxhighlight>
 
  
==JS and DOM==
+
<br />
'''Based on the [[Web Development#Document Object Model (DOM)|DOM]], JavaScript gets all the power it needs to create dynamic HTML:'''
+
===Some of the most important methods===
* JavaScript can change all the HTML elements in the page
+
https://www.w3schools.com/js/js_intro.asp
* JavaScript can change all the HTML attributes in the page
 
* JavaScript can change all the CSS styles in the page
 
* JavaScript can remove existing HTML elements and attributes
 
* JavaScript can add new HTML elements and attributes
 
* JavaScript can react to all existing HTML events in the page
 
* JavaScript can create new HTML events in the page
 
  
In javascript the root element is defined by the javascript object '''document'''
 
There are a number of functions we can use to 'traverse' or interrogate the document object i.e. elements of the DOM
 
  
'''docuemnt object:'''
+
<br />
In javascript the root element of the DOM is defined by the javascript object '''document'''.
+
====Change HTML Content====
 +
This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":
 +
<syntaxhighlight lang="javascript">
 +
document.getElementById("demo").innerHTML = "Hello JavaScript";
 +
</syntaxhighlight>
  
  
'''There are a number of functions''' we can use to 'traverse' or interrogate the document object i.e. elements of the DOM:
+
<br />
 +
====Change HTML Attribute Values====
 +
This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":
 +
<syntaxhighlight lang="javascript">
 +
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>
  
'''getElementById''' function allows to pick one element from the DOM tree and check to see what the values current are
+
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<syntaxhighlight lang="php">
 
document.getElementById('id') // we pass the id of the element
 
</syntaxhighlight>
 
  
'''document.getElementById(‘id’).value''' allows to extract the value of an element.
+
<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>
 
 
'''createTextNode''' is used to make a new node (to add new elements to the DOM tree):
 
<syntaxhighlight lang="php">
 
var txt = document.createTextNode(" This text was added to the DIV.");
 
document.body.appendChild(txt);
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
  
 +
<br />
 +
====Change HTML Styles - CSS====
 +
This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":
 +
<syntaxhighlight lang="javascript">
  
'''Javascript Events:'''
 
 
When we want a function to be called when something happens on a page, we use '''event handlers'''. These are just like the ActionListener and ActionPerformed in Java.
 
 
When a button is pressed, for example, we can call a function:
 
When a button is pressed we can call a function:
 
<syntaxhighlight lang="php">
 
<button onclick=’callFunction()’>Submit</button>
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
===Example 1===
 
When we call the function '''document.getElementById''' it will return is a reference to the element in the DOM tree where that element is. Once we get this reference, we can then make changes to the element. The '''innerHTML''' function allows us to set the HTML of an element dynamically.
 
  
/var/www/html/webdevelopment/lecture10-JS/2DOM.html
+
<br />
<syntaxhighlight lang="php">
+
====Hide HTML Elements====
<html>
+
This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":
 
+
<syntaxhighlight lang="javascript">
<head>
 
</head>
 
 
 
<body>
 
      <div id = 'demo'>
 
            <p>This is some content</p>
 
      </div>
 
</body>
 
 
 
<button onclick='updateDivAdelo()'>Submit</button>
 
  
<script>
 
      function updateDivAdelo() {
 
            document.getElementById('demo').style.color='blue';
 
            document.getElementById('demo').innerHTML = '<p>This is some new content on blue</p>';
 
      }
 
</script>
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
===Javascript Validation===
 
  
  /var/www/html/webdevelopment/lecture10-JS/3CSValidationJS.php
+
<br />
<syntaxhighlight lang="php">
+
====Show HTML Elements====
<html>
+
This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":
 +
<syntaxhighlight lang="javascript">
  
<head>
 
</head>
 
 
<body>
 
      <form id='form' action='3CSValidationJS.php' method='post' onsubmit="return validate()">
 
            username: <input type='text' name='username' id='username'><br/>    <!-- name es usado por PHP, pero js se base en el id -->
 
            email:    <input type='text' name='email' id='email'><br/>
 
                      <input type='submit' value='Submit'>
 
      </form>
 
</body>
 
 
<script>
 
      function validate(){
 
            var uname = document.getElementById('username').value;
 
            // if (uname == ''){
 
            if (uname.trim() == ''){ // con trim, los espacios no son considerados
 
                  alert("Username debe ser definido");
 
                  return false;
 
            }
 
            else if (uname.length <= 3){
 
                  alert("Username must be more than 3 chars!");
 
                  return false;
 
            }
 
            else{
 
                  return true;
 
            }
 
      }
 
</script>
 
 
</html>
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
==Javascript Debugging==
 
When using javascript in a browser it's vital that we are comfortable using the browser’s developer tools to debug javascript code.
 
  
The first port of call should be the '''console window''' in the developer tool. This will flag any errors when we refresh our web page. Hopefully there will be helpful messages to allow us to fix our code. Syntax errors etc should show up here.
+
<br />

Revision as of 13:46, 14 October 2019

https://www.w3schools.com/js/default.asp

JavaScript and Java are completely different languages, both in concept and design.

JavaScript is one of the 3 languages all web developers must learn:

  1. HTML to define the content of web pages
  2. CSS to specify the layout of web pages
  3. JavaScript to program the behavior of web pages

Web pages are not the only place where JavaScript is used. Many desktop and server programs use JavaScript. Node.js is the best known. Some databases, like MongoDB and CouchDB, also use JavaScript as their programming language.



What JavaScript can do

What JavaScript can do / What is used for / some of the most important methods:

  • JavaScript Can Change HTML Content
  • JavaScript Can Change HTML Attribute Values
  • JavaScript Can Change HTML Styles (CSS)
  • JavaScript Can Hide HTML Elements
  • JavaScript Can Show HTML Elements



Installation


IDE for JavaScript


Control flow statements


If statements


For Loops


While Loops


Methods


Some of the most important methods

https://www.w3schools.com/js/js_intro.asp



Change HTML Content

This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":

document.getElementById("demo").innerHTML = "Hello JavaScript";



Change HTML Attribute Values

This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>



Change HTML Styles - CSS

This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":



Hide HTML Elements

This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":



Show HTML Elements

This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":