Difference between revisions of "JavaScript"

From Sinfronteras
Jump to: navigation, search
(Created page with "* Javascript runs on the client side in the browser. * Javascript code is interpreted by the browser. * In JavaScript, instructions are called statements and are separated by...")
 
Line 3: Line 3:
 
* In JavaScript, instructions are called statements and are separated by a semicolon (;).
 
* In JavaScript, instructions are called statements and are separated by a semicolon (;).
  
 +
 +
<br />
 +
==Script tag in a html file==
 
* <script> tag allows us to include a piece of Javascript in a HTML document:
 
* <script> tag allows us to include a piece of Javascript in a HTML document:
 
<syntaxhighlight lang="php">
 
<syntaxhighlight lang="php">

Revision as of 13:17, 14 October 2019

  • Javascript runs on the client side in the browser.
  • Javascript code is interpreted by the browser.
  • In JavaScript, instructions are called statements and are separated by a semicolon (;).



Script tag in a html file

  • <script> tag allows us to include a piece of Javascript in a HTML document:
<h1>Testing alert</h1>
<script>alert("hello!");</script>
  • 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.
<h1>Testing alert</h1>
<script src="js/myfile.js"></script>
  • 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:
var input;
if(input === undefined){
     doThis();
}else{
     doThat();
}
  • 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:
x = "The answer is " + 42 // "The answer is 42"
y = 42 + " is the answer" // "42 is the answer"
  • In statements involving other operators, JavaScript doesn't convert numeric values to strings. For example:
"37" - 7 // 30
"37" + 7 // "377"
  • Javascript Strings:
    • The + operator can be used to concatenates strings:
    • The following line will produce the string "concatenate":
"con"+"cat"+"e"+"nate"
  • To output debug statements (on the Terminal) the console.log() function is used, similar to echo in php:
var = 10;
for (var i=0 ; i<10 ; i++){
     console.log("Loop value: "+i);
}
  • Javascript Arrays:
    • JavaScript provides a data type specifically for storing sequences of values. It is called an array. The
var myArray = [];  //empty array

var listOfNumbers = [2, 3, 5, 7, 11];
console.log(listOfNumbers[1]);
console.log(listOfNumbers.length)
  • We can determine the length (or number of elements) of an array using the .length property
console.log(listOfNumbers.length)
  • Array iteration:
var myArray = ['none','two','three','four','five','six'];
for (var num in myArray){
     console.log(myArray[num]);
}
  • indexOf
var myArray = ['one','two','three','four','five','six'];
myArray.indexOf('two');  // 1
  • Functions in Javascript come in many forms. But predominantly we can have:
    • named, or
    • anonymous functions.
  • A named function looks something like this:
// Define a function
function myFunction() {
     console.log("function called");
     // do something interesting
}

myFunction(); //execute the function
  • An anonymous function is a function without a name. It is generally assigned as a variable value:
var func = function(){
     console.log("Anonymous function executed...");
}

func();  //Execute the function
  • All functions can accept parameters and can use the return keyword:
function myFunction(var1, var2, var3){
     newValue = var1 + var2;
     console.log(newValue + var3);
}

var returnValue = myFunction(12, 13, 30);
console.log(returnValue);

JS and DOM

Based on the DOM, JavaScript gets all the power it needs to create dynamic HTML:

  • JavaScript can change all the HTML elements in the page
  • 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: In javascript the root element of the DOM 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:

getElementById function allows to pick one element from the DOM tree and check to see what the values current are

document.getElementById('id') // we pass the id of the element

document.getElementById(‘id’).value allows to extract the value of an element.

createTextNode is used to make a new node (to add new elements to the DOM tree):

var txt = document.createTextNode(" This text was added to the DIV.");
document.body.appendChild(txt);


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:

<button onclick=’callFunction()>Submit</button>

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
<html>

<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>

Javascript Validation

 /var/www/html/webdevelopment/lecture10-JS/3CSValidationJS.php 
<html>

<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>

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.