Category Archives: Javascript

JavaScript (frequently abbreviated JS) is an interpreted programming language, dialect of the standard ECMAScript. It is defined as object-oriented, prototype-based, imperative, weakly typed, and dynamic

Javascript

Javascript

JavaScript, just like Java or VRML, emerged to extend the capabilities of the language HTML and get dynamic web pages

JavaScript is not a programming language itself

It is a scriptor or document-oriented language, such as macro languages that have many word processors. You will never be able to make a program written in JavaScript, you can only improve your website by inserting javascript code in it

Utility of JavaScript

JavaScript serves primarily to improve client/server interface management. A JavaScript script embedded in an HTML document allows you to recognize and treat user-generated events locally, that is, on the client. These events can be the journey of the HTML document itself or the management of a form

For example: when the HTML page is a form that allows access to a phone book, you can insert a script that verifies the validity of the user-provided parameters. This test is done locally and does not need network access

On the other hand, you can also use JavaScript to make several options at once; for example, viewing a video within an HTML document or running a Java applet...

Differences with Java

The main difference between JavaScript and Java is that the latter is a complete programming language. Although they share the same syntax

JavaScript is a language that integrates directly into HTML pages. It has as its main features the following:

  • It is interpreted (not compiled) by the client, that is, the source program is executed directly, unlike in the compiled languages, neither object or executable code is generated for each computer on which you want to run that program
  • It's object-based. It is not, like Java, an object oriented programming language (OOP). JavaScript does not employ classes or inheritance or other typical OOP techniques
  • Your code is integrated into the HTML pages, included in the pages themselves
  • You don't need to declare the types of variables to be used, JavaScript performs an automatic type conversion
  • Object snaps are checked at run time. This is a consequence of JavaScript not being a compiled language
  • It is not possible to work directly with files, or automatically write to the hard drive. That's why JavaScript is said to be a safe language for internet users

Use of JavaScript in an HTML document

Inserting an HTML document is done using the SCRIPT mark using the syntax:

The attributes of this mark are:

  • type=“text/javascript”
    Specifies the language of the script. This attribute is required in the absence of the SRC attribute
  • src=url
    The SRC attribute specifies the URL of the script to insert into the document. This attribute is optional, because the script can be inserted directly into an HTML document

It can be specified to insert a script of a particular language into a document and whose source code is in a file specified in a particular url. It can be useful if we want several of our web pages to share the same scripts without having to insert them into each one, repeating the code

Here are some points to keep in mind regarding the introduction of JavaScript in an HTML document:

  • The script inserted via the brand SCRIPT it is evaluated by the client after the display of the page HTML. The defined functions do not execute immediately, depending on the events associated with the page
  • The insertion of the script by using the brand SCRIPT can be placed anywhere in the document HTML but it is recommended to place it in the header, that is, in the area defined by the HEAD. In this way, the script is defined from the beginning of the document, ensuring that the document is visible throughout the document
  • If defined, in addition to the script using the SRC, scripts in the document itself, the client will first evaluate the inserted using the SRC and then included in the document
  • The URL corresponding to a JavaScript have generally the extension .js
  • It is preferable to delimit the scripts inserted into a document-by-document comments HTML to ensure that the contents of the script will not appear on clients that do not recognize the brand SCRIPT. For example:
  • The JavaScript language is not case sensitive, except in literal character strings

Finally, comment on another way to introduce scripts in HTML documents, and is to include these scripts as event handlers for some brands, such as image marks, anchors, links, buttons, etc. Let's look at an example:

Go to the index

As you can see, within this mark, as an attribute of this, an event handler is put and after the equal sign and in quotation marks The JavaScript code is included. However, it is also possible to call a function from the HEAD document. This second option is recommended as it is a cleaner and clearer way to write pages. The same result would be achieved as in the previous example:

Versions of JavaScript

The language was invented by Brendan Eich in Netscape Communications. It first appeared in Netscape Navigator 2.0. Which included JavaScript under the name Mocha, when this version of Navigator appeared it was called LiveScript. It was finally renamed JavaScript in a joint ad between Sun Microsystems and Netscape on December 4, 1995

Traditionally, it had been used in HTML web pages, to perform tasks and operations within the framework of the client-only application, without access to server functions. JavaScript was running in the user's browser at the same time as the statements were being downloaded along with the HTML code. What Netscape wanted is for JavaScript to be a scripting language, easy to use and for anyone to use. After 2 years JavaScript became one of the most used tools by web developers, using almost 90% of web developments, even more than Java and Activex

Netscape introduced a server side script implementation with Netscape Enterprise Server, released in December 1994 (shortly after the release of JavaScript for web browsers)

In 1996 Microsoft began to show great interest in competing with JavaScript so it launched the language called Jscript, which was the implementation of ECMAScript, very similar to Netscape's JavaScript, but with some differences in the object model of the browser that would make both versions incompatible. But version 4.0 of Internet Explorer without any problem supported JavaScript version 1.1. However, Jscript was unable to compete directly with Javascript

In mid 1997, Netscape promoted JavaScript and released version 1.2. This new version included new components that gave great potential to the language, but unfortunately this version only worked on the latest version of the Navigator. The authors proposed that it be adopted as the standard of “the European Computer Manufacturer’s Association” (ECMA, with the ECMAScript implementation), which despite its name was not European but international, based in Geneva. Shortly after it was also proposed as an ISO standard

Version 1.3 was a small revision of 1.2, which was included in version 4.07 of the Netscape Navigator

To avoid these incompatibilities, the World Wide Web Consortium designed the Document Object Model (DOM) standard, which incorporates Konqueror, versions 6 of Internet Explorer and Netscape Navigator, Opera version 7, and Mozilla from its first version

Since mid 2000s, there has been a proliferation of JavaScript implementations for the server side. Node.js is one of the notable examples of JavaScript on the server side, being used in important projects

The arrival of Ajax returned JavaScript to fame and attracted the attention of many programmers. As a result, there was a proliferation of a set of frameworks and libraries of general scope, improving programming practices with JavaScript, and increasing the use of JavaScript outside web browsers, with the proliferation of server-side JavaScript environments. In January 2009, the CommonJS project was inaugurated with the objective of specifying a library to use common tasks mainly for development outside the web browser

In June 2015, the ECMAScript 6 standard (latest version to date) was closed and published with irregular support between browsers and that provides JavaScript with advanced features that were missed and that are commonly used in other languages such as, for example, modules for code organization, true classes for object-oriented programming, date expressions, iterators, generators or promises for asynchronous programming

Comments in JavaScript

The comments in the code allow the author's comments to be inserted to describe the different parts of the program. The JavaScript interpreter ignores them and therefore has a particular syntax

Comments on a single line are distinguished, preceded by the double slash // and comments on several lines delimited by the symbols / * and * /. For example:

Identifiers and reserved words

To know what is the syntax of the identifiers which are reserved words is something that is necessary before you start to write a program in a particular programming language

The identifiers of a language are the string of characters that we assign to the names of variables, constants, functions, objects, etc ..., which we define in that language, these are necessary to be able to invoke said elements in places after their definition

Identifiers must follow the following rules:

  • The identifier must start with a letter or the character '_'
  • The following characters, in addition to letters or the '_' character, can be figures

Note that case is not important, because JavaScript does not differentiate from case names in identifiers. Let's look at some examples of variable names:

First, say that reserved words are special words that are used to increase readability and separate syntactic entities. These words cannot be used as identifiers

Next we will see a table in which all the existing reserved words in JavaScript are shown, these words have or will have a special meaning within the language:


Reserved words
Abstract
Boolean
Break
Byte
Case
Cath
Char
Class
Const
Continue
Default
Do
Double
Else
Extends
False
Final
Finally
Float
For
Function
Goto
If
Implements
Import
In
Instaceof
Int
Interface
Long
Native
New
Null
Package
Private
Protected
Public
Return
Short
Static
Super
Switch
Synchronized
This
Throw
Throws
Transient
True
Try
Var
Void
While
With

Operators in Javascript

Operators in Javascript

JavaScript has a wide variety of operators

These operators can be distinguished into two groups: binaries, which act on two operands and unaries, which only require one operand

Thus, its general syntax is:

operand1 operator_Binary operand2

operand1 operator_unary

operator_unary operand1

Arithmetic operators

JavaScript provides the basic operations with the only operator additive that returns the rest of the division between the left and the right operator. More complex operators are lacking, although the Math object defined in JavaScript has these tasks

Arithmetic operators
+ Addition
Subtraction
* Multiplication
/ Division
% Rest

Note The operator + applied to strings concatenates both strings in one

Operators of increase (++) and decrease (- -)

These operators are unary and perform the self increment and self growth to the variable that applies to them. In addition to modifying the variable, they return the value of it

The operator increment or decrement can go before p behind the variable having a different meaning

If the operator is ++, it is placed after the variable is called post-increment, by first taking the value and then increasing the variable by one unit

If the ++ operator is placed before the variable, it is called pre-increment and makes that first to increase in a unit variable and then take the value

If the operator is - - it is placed after the variable, it is called post-decrement, making it take the value first and then the variable is decremented by one unit

If the operator - - is placed before the variable, it is called pre-decrement and makes that first decremente in a unit variable and then take the value

Relational operators

They are typically used in conditional expressions. Relational operators return Boolean values. The operands can be both numerical and strings

Relational operators
> Greater than
< Less than
> = Greater than or equal to
< = Less than or equal to
! = Other than that
= = Like

Logical operators

Logical operands are related to relational ones since normally the operands they use are the result of relational expressions. The resulting values are Boolean

Logical operators
& & AND
| | OR
! NOT

Bitwise operators

The way of working of these operators is to convert to the binary operands and then operate with them bitwise

Bitwise operators
& AND
| OR
^ XOR
<< Propagation to the left
Shift the value to the left by entering zeros, if it goes out of range, values are lost
>> Spread to the right
Moves the value to the right entering by the left, the sign bit and eliminating the values that are out by the right
>>> Zero fill, right propagation
Similar to &lt;&lt; but to the right. Do not enter sign bit

Note Propagation operators take two operands: the first is the variable to propagate and the second is the number of positions to propagate

Assignment operators

The assignment is also an operator that returns the modified variable. The assignment operator in JavaScript is =. The assignment operators shown below are nothing more than abbreviations that make expressions more comfortable and simple, although sometimes they are more illegible

Assignment operators
Operator Expression Equivalence
= A=B=C; A=C;
B=C;
+ = A + = 4; A = A + 4;
– = A – = 3 * B; A = A – (3 * B);
* = A * = 2; A = A * 2;
/ = A / = 35 + B; A = A / (35 + B);
>> = A >> = 1; A = A >> 1;
<< = A << = B; A = A << B;
>>> = A >>> = B + 1; A = A >>> (B + 1);
& = A & = (C + = 3); C = C +3;
A = A & C;
^ = A ^ = 2; A = A ^ 2;
| = A | = C; A = A | C;

Other operators

Selection operator

This operator is used to execute one operation or another depending on the condition. The format is as follows:

Condition ? Exp1 : Exp2

If the condition is met, the expression Exp1 is returned and if the Exp2 is not. We can put only one value. Example:

New operator

This operator is to be used to create an instance of a previously defined type of object. The syntax to follow is as follows:

variableObject = new ObjectType(parameter 1, parameter 2, …)

These parameters are passed to the constructor of that object in question

Typeof operator

This operator applied to a variable returns the type of object to which the data contained by that variable belongs. Its syntax is:

typeof(variable)

Preference

The preference of the operators will determine the order in which they are executed in a given expression. Using parentheses we will control that the operations are carried out as we want. In JavaScript, the preference of operators from highest to lowest is as follows:

Preference
Negation / (in / de) crease ! ++
Mul / Div / Rest * / %
Addition / Subtraction +
Spread << >> >>>
Relational < < = > > =
Equality = = !=
Bitwise AND &
Bitwise XOR ^
Bitwise OR |
AND logic &&
A logical OR | |
Other operators ?: New Typeof
Assignment = + = – = * = / = >> = << = >>> = & = ^ = | =

Javascript data types

Javascript data types

Types in Javascript are a representation of data because it does not require variables to declare their type, because all types are automatically converted

Type boolean

The Boolean type simply distinguishes between two states, a success or enabled state, true value, true, and a failure or deactivated state, false value, false

Numeric types

The numeric types can be divided into real and integer

Type integer numeric

  • Decimal

    integer base 10

    Both positive and negative

  • Hexadecimal

    integer base 16

    Placed before the base number 16 0x or 0X

  • Octal

    integer base 8

    We place a zero before the number in octal

Numeric type real

The actual is made up of a whole part and the other fractional separated by a point of the previous

The fractional part can be composed by an indicator of exponent E or E followed by an integer that indicates the value of the exponent

Type string

A string is a string of characters delimited by quotation marks

The quotation marks will be single or double according to a particular rule

The default is to use double quotation marks ("), but if any statement to be included in those quotation marks, if that statement contains a string or in turn another statement that must also be delimited by those quotation marks, these quotation marks will then be single quotation marks (')

On the other hand, we must take into account the writing of special characters in what we call escape sequences

The escape sequence always begins with the character \ and then another character is written that represents the special code or the number in octal or hexadecimal of its ASCII code

Escape sequences represent a single character in the strings in which they appear

Code Description
a Sound
b White
f Line break
n New line
r Carriage return
v Vertical tab
\ Blackslash "\"
Single quotation mark
" Double quotation mark
Ooo Ascii in octal
Xhh Ascii in hexadecimal
t Horizontal tab

Arrays

We can create arrays that we will give a name and that we will access with an index that will start from element number 1 (not from 0 as in Java or in C / C++)

In the arrays as with variables, there are no default types

To create an array it is necessary to define a function like the one below:

Comment on the function that the reserved word this refers to the current variable, that is, the variable that will contain the array

On the other hand, to observe that arrays have a length property that shows us the length of that array

Finally show the use of this function:

Objects

Objects consist of a set of values, properties, and a set of methods applied to those values

It is these methods that allow us to modify the state of that object, that is, the value of its properties

In JavaScript there are predefined objects

In addition, the programmer can also create his own objects

To make use of the properties of an object, simply use the following notation:

my_object.property

This will be seen more clearly in the following example, in which we have a University object in which we have the properties: Name, Last Name, Age and Faculty

Assuming we have a Uni1 variable that contains a University object at any given time:

But not only can we access the properties of an object by using the notation above, because, there is a relationship between objects and arrays, since we can access an object as if this were an array and its elements were the properties of object in the order in which they were defined

This type of vectors are referred to as associative arrays

A method it is a function assigned to an object

The following syntax is used to assign a function as a method of an object:

We can observe that the name of the method is the way in which we want to name the function within the object

A method can be called in a context using the syntax:

Object.methodName(parameters);

The reserved word this allows us to reference the current object

For example, suppose that the validate function allows you to validate the properties of an object through an associated minimum and maximum; we will have:

You may call then the function validate to change the values of a form by using the reserved word this and the attribute OnChange to detect the changes of values

This is done through the HTML flag and the event:

In general, the word this refers to the current object

The client and the server have a set of predefined objects that can be completed using new objects. The creation of an object is done in two stages:

  1. The object is defined by a function
  2. Create an object using the reserved word new

To define an object, a function will be created to specify its name, its functions and its associated methods

For example, if you want to create a university object whose properties would be name, surname, age and DNI, the following generic function will be defined:

The object instance will be created as follows:

The properties of an object can be described by other objects

We make the university object have a property of the Note_Mean object therefore:

Therefore, to access the final note:

student.expedient.final

When an object is defined, it is possible to enrich its description through new properties

student.dni = 44567234;

Now the property id belongs to the instance of the object contained in the student

This modification will not affect the other objects of the university type, since to add a property to an object type it must appear in its definition

The definition of methods associated with an object can be specified in the object definition

For example, for the university object we define a function that shows the name, surname, DNI and faculty of a student

This function becomes a method associated to the type by performing in its definition the following:

Its use will be:

student.Data();

The following example shows the function of the type of university that we have created

To do this we create the following form:

The Show_Univers (form) function is defined as follows:


Average mark of the academic stage



Note Have not checked if the data that is inserted in the form are "correct", that is, if the notes are between 0 and 10, if the first and last names are composed only of letters or the age is numerical

Null value

In JavaScript variables can be assigned a value that indicates the empty value, this value is null

The conversion of data types

First of all, remember that JavaScript doesn't need type declaration

The contents of the variable will be converted automatically in the course of the programme according to its use

The type conversion scheme is based on the following principle: the associated type corresponds to that of the left operand

This is because the evaluation is done from left to right

For example, suppose you define the following variables:

If we evaluate the following expressions

The first expression will convert the a_number variable to a character string because the operand on the left an_string is a string of characters

This expression concatenates the two character strings and the result of x is:"742"

Conversely, the second expression converts the string an_string to a numeric value because the left operand a_number, is as its own name indicates, a number

This second expression sums the two numbers and the result of y is: 49

Type conversion cannot be done in all possible cases: certain character strings cannot be converted to number

Such conversions fail with an error

For example:

Table that summarizes type conversion in JavaScript:

Type Function Object Number Boolean String
Function Function Error Error Descompila
Object Error Error True ToString
Null object FunObj ok 0 False “null”
Number Error Number True ToString
Number = 0 Error Null False “0”
Boolean = true Error Boolean 1 “true”
Boolean = false Error Boolean 0 “false”
String Single quotation mark String Numstr ok True
String null Error String Error False

Control structures in Javascript

Control structures in Javascript

For control structures, JavaScript has the typical control sentences of high level languages

Variable statement

Variables in JavaScript are not assigned a predefined type

In JavaScript the type of the variables depends on the value that contain the same in each time

Therefore it performs an automatic conversion of types

JavaScript recognizes the following types of values:

Since there are no types of a priori variables, we do not have to specify the type of variable when declaring it

The declaration of variables is done by prepending the reserved word var to the name of the variable

It is possible to assign the value when we declare

The if sentence

The if sentence has the form:

The parentheses associated that define the condition are not optional

If the condition is true, instruction 1 will be executed; otherwise it is executed if there is instructution 2

The use of the sentence else is optional, so brackets have been used in the definition

If omitted, the instruction block will only be considered when the condition is true

A block of instructions is a set of instructions bounded by curly brackets

Keys after sentencing if are not required

If omitted and the condition was true, the following instruction will be executed

Otherwise, the subsequent instruction will be executed, independent of the condition state

Thus, the omission of keys after the sentence if it will allow us to write everything on a single line finished in ;

The else if sentence

We can also use sentences if anities by sentencing else if

Sentences else if work just like a sentence if

But they will only be executed in case the condition of the sentence if was false

The switch sentence

Makes is select a group of sentence among several possible

It is an alternative to the use of sentences else if anities

Its syntax is:

The expression between parentheses of the switch must be whole

Your result will be compared with the different values of the case

If it matches one of them, the following sentence will be moved to the case with that value and consecutive instructions will continue to be executed until a sentence is found break or reach the switch lock keys

In case the result of the expression does not match any value, execution will be passed to the next statement sentence on the label default, if there were, and it will continue as a case

The values in the case can be a constant expression

There can be two case with the same value

The while sentence

The while sentence has the form

The parentheses are not optional

If the condition is met, the sentence or instruction block is executed and the process is repeated until the condition is no longer met

The do sentence

The do sentence has the form

It's very similar to the sentence while, except that the condition goes after the instruction or block of instructions

So they are executed at least once even if the condition is false

The for sentence

As for such a sentence, in JavaScript we can distinguish two variants:

  • The loop for "classic"
  • The loops for / in

The loop for "classic"

This loop has a syntax very similar to that of C / C+

In this syntax:

Initialization creates the counter variable and gives it an initial value

Condition must be fulfilled for the loop to run

Depends on the variable index

Expression updates the value of the variable index

The equivalent of this while expression is:

The loops for / in

This loop has a syntax very similar to the for-each Java

Iterates a variable var over all the properties of an object obj that is passed to it

Thus, for each value of var is is executed, the judgments of the loop

Therefore, the loop will have as many iterations as the object's properties, and in each iteration the variable will have the value of the corresponding object's property with that iteration

Its syntax is:

The break sentence

The break sentence can be placed within a loop or anities loops

When you execute the break sentence exits the loop more internal

To all effects, the break sentence acts as a jump to the sentence following the loop in which it runs

The continue sentence

The continue sentence does not leave the loop but causes the next iteration to run

In the loop while the execution of the continue causes the program flow to jump to the condition

In the for loop the continue execution causes the increment expression to run, and then continue normally with the condition

That is, running the continue prevents the rest of the loop body from running

Functions in Javascript

Functions

To define functions we have the instruction function

After this reserved word is placed the name of the function followed by a list of arguments delimited by parentheses and separated by commas

The return statement

The statement return it is the one that allows you to return the result of a function

The example shows a function that returns the area of a square of side l

Properties of the functions

JavaScript associates two properties with each function:

  • arguments
    it allows the management of the optional parameters
  • caller
    identifies the function that made the call

The property arguments

Is an array that contains the parameters that are passed to the function

In the example we have defined the Sum function to calculate the sum of the numbers passed as arguments

Thus, Sum(4,5,7) returns 16 and Sum(56) returns 56

The caller property

Displays the name of the calling function, so this property will return a string of characters

Considerations to be taken into account

Before you start working with features, you need to consider the following points:

  • The JavaScript language does not allow the definitions of nested functions

  • The passing of parameters is done by value

    That is, if a function modifies the content of its arguments, this modification is local and does not affect either globally or the function made the call

Functions are predefined by the language

Eval function

Has as argument an expression and returns the value of the same

This function is useful to evaluate a string of characters that represents a numeric expression

The issue was effected through a form field is a string of characters that it is sometimes necessary to convert to a numeric value

The following example illustrates how allowing the user to enter a numeric expression you can visualize it as the value of the expression

If you haven't entered anything, you see undefined and if it's not a numerical expression, it doesn't make changes to the visualization


Functions escape and unescape

These two functions allow you to encode strings in URL format

This encoding is necessary in the automatic creation of hypertext links or in the definition of persistent properties as the Cookies

Function isNaN

Function that checks if the value passed for the parameter is numeric or not

The result of this function is a Boolean

That is, it evaluates an argument to see if it is NaN: (Not a Number)


Function parseFloat

Converts a string of characters to a floating-point number

If a non number character is found, the sign '+', '-' or exponent, returns the value found up to that point

Similarly, if the first character cannot be converted to number it will return zero


Function parseInt

Converts a string of characters to an integer number with a specified base

La base puede ser 8, 10 ó 16

If a non number character is found, the sign '+', '-' or exponent, returns the value found up to that point

Similarly, if the first character cannot be converted to number it will return zero

jQuery

jQuery

jQuery is a library of free software written in Javascript, with MIT License and GNU General Public v2, allows its use in open source projects and private

In line with the principle type less, do more

To achieve this, it allows you to write Javascript code in a simpler way, doing in a single call tasks that requeririan several lines of code

Simplifies many of the tereas common, such as the handling of the DOM, CSS properties and an AJAX call, in addition to allowing the creation of effects or animations

Installation

Download the library in its most stable version from their official website jQuery.com

We load the library in the head of our HTML code:

In the example, version is the current number of version, may vary at the time of your download

It is advisable that in production you use the version min, since it is optimized for faster loading in the browser

There are also repositories CDN third-party that can be viewed on the official website of downloads, us librarian of having to update the current version of the library

However, we run the risk of having security flaws if someone outside of the introduction of malicious code in those repositories, or remain inacesibles for any reason

To include them simply modificariamos the src with the url of the repository CDN to indicate to us

Load the code

We can typically include the code of jQuery inside a script block like we do with Javascript, or use an external file .js where we include our own code

To be able to execute our instructions will be useful that the DOM of our HTML has been completely loaded, but we can execute them before that happens

In the example we have opted to load the DOM tree when it has loaded the HTML completely, including our code inside of the curly braces

In this other example we have an equivalent version that allows us to write less code, choose the one you like the most, although the first is more clear

Basic syntax

The jQuery syntax is very similar to CSS because all of the calls are composed of a selector followed by a call

In the example we can see the $ symbol that allows us to access the elements of jQuery

The selector will allow to select specific elements within the DOM tree

The action will be a function that allows us to interact with the item selected by the selector

In the examples we have the operator this, which represents the current item selected

‘p’ a tag is HTML valid, which represents an element, here we will be able to use any of them to perform searches

When we see with more detail the selectors, we will deepen in how they should be those searches

‘.test’ uses the symbol . to refer to what follows after that is a class, in this case, the test class

‘#test’ use the # symbol to refer to that what follows is an id, in this case, the id test

Selector

Selector

A selector allows us to specify what elements we want to apply the action

There are the following types of selector:

  • Item
  • Class
  • Id

Item

It is possible to select an element directly according to their type of HTML tag

In this example we have selected all of the elements of type paragraph

In this example will be hidden all the elements of type paragraph when you press on the item type button

Class

It is used with the symbol . and allows us to select elements with a specific class

In this example we have selected the element of the test class

In this example will be hidden all the elements of the test class when you press on the item type button

Id

Used with the # symbol and allows us to select elements with an id specific

In this example we have selected the element with the id test

In this example will be hidden all the elements with the id test when you press the element type button

Practical example

More examples of selector

Events

Events

The actions that the user performs or the changes you make in the page are known under the name of events

An event is the sign that 'something' has happened

Syntax of events

You need to specify a selector, to know which element the event will interact with, followed by the event in parentheses

We will use the following sample HTML, that contains a simple form, to get to know the use of the events, accompanied by a file that we will call event.js

To process the form, we have also added a file form.php however, we are not going to use the examples on events

Item events

This type of event is that normally used by the user to interact with the elements of the HTML, when you hover the mouse over the element or is pressed, among others

Among the most important of which we highlight:

  • focus

    is triggered when the focus goes to the element

  • blur

    is triggered when the focus goes to another element or lose it

  • click

    is activated when you click on the element

  • dblclick

    is activated when you double click on the element

In the example we have selected the element with the id button, and responds to the click event that has as a parameter the variable warning

It could have included the code inside the click event, but wanted to emphasize that the parameters can be a variable that contains a function, so we can have different variables with different behavior, without having to modify our code

Mouse events

Occur when the user uses the mouse within the HTML document or any of the elements that compose it

Among the most important of which we highlight:

  • mousedown

    turns on when you press a mouse button

  • mouseup

    is activated when you stop pressing a mouse button

  • mousemove

    is triggered when the mouse moves

  • mouseover

    is triggered when the mouse moves over an item (when we enter in the item)

  • mouseout

    is triggered when the mouse leaves the element (when we leave the element)

In the example, we have added a couple of events that change the type of letter when you pass the mouse over the element with id button

It is possible to assign to these event parameters that contain information about a mouse event

Among the most important of which we highlight:

  • screenX and screenY

    represent the coordinates of the mouse pointer with respect to the global coordinates of the screen

  • clientX and clientY

    represent the coordinates of the mouse pointer with respect to the browser window

  • button

    is the number of the button that has been pressed (left = 0, center = 1, right = 2)

    If you do not want to pass it as a parameter, we can use the property buttonsthat includes more buttons, as the mouse wheel or the forward and back buttons of the browser

In the example we have modified the variable warning to detect which button has been clicked and what position you had the mouse on the screen, when it has been clicked

Keyboard events

Occur when the user uses the keyboard

Among the most important of which we highlight:

  • keydown

    turns on when you press a key

  • keyup

    is activated when you stop pressing a key

  • keypress

    is activated when you press and stops the press of a key

It is possible to assign to these event parameters that contain information about the event from the keyboard

Among the most important of which we highlight:

  • char or charCode

    is a string with the character that has been pressed (provided that the same is representable)

  • key or keyCode

    it is an identifier that represents the key that has been pressed

    You can see the complete list on the page for developers Mozilla

  • ctrlKey,, shitKey and altKey

    these are fields that indicate whether the key Control, Shift or Alt key had been pressed when the event occurred keyboard

In the example has been added to the variable key with parameters to capture the keystrokes when you type in the element with the id login, and has modified the set of calls to use, using the keypress event

Touch events

These events are produced by touching a touch screen

Are similar to those produced by a mouse, but its delay is much lower

Because of this, conflicts can occur with mouse events, this is why it is advisable to disable them, not to run similar events twice

Among the most important of which we highlight:

  • touchstart

    is activated when the finger touches the surface of the screen

  • touchend

    is activated when the finger stops pressing the surface of the screen

  • touchmove events

    is activated when the finger slides on the surface of the screen

  • touchenter

    is activated when the finger is moved over an item (when we enter in the item)

  • touchleave

    is triggered when the finger leaves the element (when we leave the element)

  • touchcancel

    is activated when the finger goes outside the bounds of the browser window

Form events

The forms have their own events, among the most important of which we highlight:

  • click

    it is activated when we click the mouse on an item
    It is usually used with buttons (button, submit)

  • change

    is triggered when the user modifies the value of a text element

    This is normally used with input of type text, textarea or drop-down lists to select an option

  • focus

    is activated when the user selects a form element

  • blur

    is triggered when the user moves to another form element

  • submit

    is activated when the user performs the action of submitting the form (not just when pressed the button submit, which can be simulated at the push of a button which makes the time of submit or when you force a call to the event from another event)

    In addition, the submit event generates the events mousedown, click, mouseup and submitin that same order, which allows us to perform validations on the form elements before final submission

  • reset

    is activated when the user performs the action of resetting the form (not only when you press the reset button, which can be simulated at the push of a button that makes the times of reset, or when force a call to the event from another event)

In the example, we have added the variables to send (to validate the fields login and pass) and write (to validate that it does not enter the @ symbol into the field, pass); has modified the set of calls to use, using the events submit and change

Modification of styles

Modification of styles

JQuery allows to modify easily the styles and the CSS properties of our web page

Add or remove CSS properties

By using the methods addClass() and removeClass() we can assign or remove a CSS class from any element

In the example, add the styles are important and color the element with id div01 when you press the button btn01, and eliminates the color style

Manipulation of CSS properties

The method css() allows us to view or modify any property of the stylesheet of an HTML element

It has the following syntax:

In case you only want to see the property, we will omit the parameter value and if we want to modify it, we'll use that parameter

In the example, we have used three paragraphs different with a style for the background color different, if you push the button with id btn03 we can see that with the css method, we have changed all the paragraphs to yellow

Effects

Effects

JQuery allows you to, in a simple way, create effects, transitions, movements, animations, etc

Hide and Show

The method hide allows you to hide an element

To be able to re-make it visible we can use the method show

In the above example when the button is clicked with id hide has used the method to hide a parameter that indicates the speed (in milliseconds) to hide the paragraph with id part01

When you press the button with id show it has been used the show method with a parameter that indicates the speed (in milliseconds) to display the paragraph with id part01

Fading

It is similar to Toggle, since the element appears or disappears, however it does gradually

We will use this example to test the different methods of fadding

FadeIn

Allows that a hidden item appears

Supports a parameter to indicate speed (in milliseconds) or values 'slow' or 'fast'

Modify the HTML in the previous example to add this script

FadeOut

Allows an element to be hidden

Supports a parameter to indicate speed (in milliseconds) or values 'slow' or 'fast'

Modify the HTML in the previous example to add this script

FadeToggle

Allows altenar between the effects of fadeIn and fadeOut on a element

Supports a parameter to indicate speed (in milliseconds) or values 'slow' or 'fast'

Modify the HTML in the previous example to add this script

Sliding

It allows us to move items to show up or down

We will use this example to test the different methods of sliding

SlideDown

It moves down the element

Supports a parameter to indicate speed (in milliseconds) or values 'slow' or 'fast'

Modify the HTML in the previous example to add this script

SlideUp

Move element up

Supports a parameter to indicate speed (in milliseconds) or values 'slow' or 'fast'

Modify the HTML in the previous example to add this script

SlideToggle

Allows altenar between the effects slideDown and slideUp to the element

Supports a parameter to indicate speed (in milliseconds) or values 'slow' or 'fast'

Modify the HTML in the previous example to add this script

Animations

It is also possible to create custom animations with the method animate() with the following syntax:

The first parameter defines a set of CSS_Properties, enclosed between the symbols { and }, that are to be modified

The second indicates the speed(in milliseconds) or the values ‘slow’ or ‘fast’

We will use this example to test various ways of doing animations

Modify the HTML in the previous example to add this script, in which we modified a single property

Modify the HTML in the previous example to add this script, in which we modified several properties

Modify the HTML in the previous example to add this script, in which we modified several properties using relative values

We modified the HTML from the previous example to add this script, in which we modified several properties by running several consecutive animations one after another