Category Archives: Web Page

A website is a document or electronic information capable of containing text, sound, video, programs, links, images, etc.

Adapted for the so called World Wide Web (WWW) and that can be accessed through a web browser

Form

Form

A form is required on any web page, as they allow the user to send data to the server

The most common example is the form of registration or login

The forms use the element form

Within this element will be the controls that make up the form, and will be of those controls which will extract the information that you will receive the server

At the time of defining a form we have to enter the URL which will receive the data and what type of HTTP method we want to use

We have the following attributes:

  • id

    it is a unique identifier, it is very useful to recognize the element from JavaScript or to process it from the server

  • name

    this will be the name of the data that will be sent with the HTTP request, can be accessed from JavaScript or from the URL indicated in the attribute action to receive the data on the server

  • action

    normally contains the URL of the application that will receive the response on the server

    For example a PHP script, although it could also be a JavaScript code file

  • method

    type of HTTP method to send the data to the server

    Maybe:

    • GET

      sends the information to the server as parameters within the URL specified in the attribute action

      These parameters will be visible in the navigation bar and it is only possible to send up to 500 bytes

      For security, it is not recommended to use this method, since the data sent is exposed in the navigation bar and someone outside the user, could manipulate them before being processed by the server

    • POST

      sends the information to the server in the same HTTP request

      You do not have the size limitation on the data sent

      Allows you to send attachments and the data sent are not visible in the browser bar

      It is recommended to use this method for security, as it makes it difficult for data manipulation before being processed by the server, although it is still possible

Input elements

The item input serves to create the vast majority of controls that can be used in a form

Depending on its attributes you can create buttons, checkboxes and even attach files

The vast majority of these controls are new thanks to the HTML5 standard such as controlling dates, colors, etc; and work through browser-specific dialog boxes

Because of this circumstance, they may differ from browser to browser or even unsupported if it is very old or does not support HTML5

It has general attributes that all elements input possess and specific attributes for each type of item

General attributes:

  • id

    it is a unique identifier, it is very useful to recognize the element from JavaScript or to process it from the server

  • name

    this will be the name of the data that will be sent with the HTTP request, can be accessed from JavaScript or from the URL indicated in the attribute action to receive the data on the server

  • type

    is the specific type of control, this attribute tells the browser what to paint on screen and what additional attributes it might contain

    So it's important that if you have specific attributes for that type, we choose them correctly or the browser will ignore them by not understanding them

  • form

    form identifier, binds the control to the form by the value of its attribute id

Specific attributes:

  • checked

    indicates that the control has been selected

    It is used only with the checkboxes and the checkboxes option

  • autocomplete

    tells the browser to fill in the field with the data entered by the user previously

    It cannot be used ely with check boxes, option boxes, or buttons

  • list

    is used to define a list of default values that will be displayed to the user as possible inputs by the user

    It cannot be used ely with check boxes, option boxes, or buttons

    It is used by associating the id of the control to an item datalist in which we will list the elements that make up the list

    These values are read-only, the user cannot modify them or add new

    The item datalist has no display associated with it, however it can be associated by its id an element label with the that we can display the value chosen from the list

  • maxlenght

    indicates the maximum length that we can use in the text entered

    Used with text box controls or those similar to it (text, password, email, url, tel, search, etc)

  • placeholder

    allows you to add a default text to give an idea to the user the type of control that is or what it is expected to enter in the same

    When used, the element is not usually used label

  • pattern

    indicates a regular expression that will be used by the browser to validate the value entered in the field

    In case the value entered does not fit the regular expression, it will display an error message to the user indicating it

    Used with text box controls or those similar to it (text, password, email, url, tel, search, etc)

  • multiple

    used with the types email and file

    Allows you to include more of an e-mail address or attach more than one file

  • readonly

    prevents the field to be modified by the user

    The browser displayed darkened to indicate to the user that can not be modified

    The value of the field will necessarily attribute value, so it needs to have some value

  • required

    tells the browser that the field is required to be some value

    It is very useful for performing validations because in case the field has not been filled in, it will display an error message to the user

Text boxes

To create a text box in the attribute type we will assign the value text

It has the specific attribute value in which is saved the default value that will be displayed to the user

Has No closing tag

The example specified a form skeleton without attributes, because we don't need it to be functional to display the various controls. We're going to do it with all the examples from now on

We've also included a text box control with the attribute value with the default value Write something here

It is a good practice to fill in this value for the user to have a visual aid of what they are expected to fill in the control

Remaining as a result:


We can also use the item datalist to show the user a list of default values as possible inputs to the text control

In the example you have specified a list of colors by using the attribute list whose value is the attribute id the datalist

In addition, we can use the attribute label to display a label with the content of the selected value

Once a value is selected, we can check that we can't modify it or add a new value, but if you delete it to choose another value from the list

Remaining as a result:



Descriptive labels

In the example above we saw how to create a text box, but for the user it might not be clear what was expected to be filled in the control

To fix it we use the attribute value to show a default value

But we can do it through a descriptive label, using the element label

A label label will be associated always with an element input

We can use two methods to perform this association:

  • inserting the control inside the label label

    Remaining as a result:


  • using your attribute for that will have as value the attribute id the control that we want to associate

    Remaining as a result:


Passwords

It is similar to the text box, but to create a password attribute type we will assign the value password

In the example we can see that the main feature of this control is that the contents of the text box is camouflaged

However, if we use the GET method that password will be visible in the browser bar

That is why it is advisable to use the POST method if you're going to enter passwords

We also have included the attribute pattern that corresponds with a regular expression that adds more security in the validation if you do not meet the format of the expression

The example expression has forced at least one number, one lowercase letter, one uppercase letter, and its length to be eight characters

Remaining as a result:


E-mail

It is similar to text box but in order to create an e-mail to the attribute type we will assign the value email

In the example we can see that the main feature of this control is that the contents of the text box are validated and if an invalid email address is entered, the browser will display an error message

We also have included the attribute pattern that corresponds with a regular expression that adds more security in the validation if you do not meet the format of the expression

In the example expression, at least one lowercase letter or number before the @ has been forced, at least one lowercase letter or number before the. and two or three letters after the.

Remaining as a result:


URL

It is similar to the text box, but to create a URL to the attribute type we will assign the value url

In the example we can see that the main feature of this control is that the contents of the text box are validated and if an invalid URL is entered, the browser will display an error message

Remaining as a result:


Phone

It is similar to the text box, but to create a phone to the attribute type we will assign the value tel

In the example we can see that there is no significant difference with respect to the text box

You could just appear any icon or special image that is generated by the browser or by using a CSS style sheet

Remaining as a result:


Search

It is similar to the text box, but to create a search to the attribute type we will assign the value search

In the example we can see that there is no significant difference with respect to the text box

You could just appear any icon or special image that is generated by the browser or by using a CSS style sheet

Remaining as a result:


Check boxes

To create a set of check boxes with the attribute type we will assign the value checkbox

In this case, the value next to the button will be the same as the attribute name and use the same to form the group of exclusive selection

Has No closing tag

In the example you have specified the choice of gender and has marked the sex Woman by default, using the reserved word checked

Remaining as a result:




Keep in mind that if we check a box it will remain checked until we uncheck it again, if we want the effect of unchecking the unelected options, we will have to use JavaScript

Boxes option

To create a set of boxes option to the attribute type we will assign the value radio

In this case, the value next to the button will be the same as the attribute name and use the same to form the group of exclusive selection

Has No closing tag

In the example you have specified a group of colors and set the color Green by default, using the reserved word checked

Remaining as a result:





Buttons

The buttons normally used to control the send and reset the form

We can add new functionalities to our form using the buttons to activate them when you press them

To do this we will use or a picture or a generic button to which you then assign JavaScript or use Jquery to provide the programming

To create a button with the attribute type we will assign the value button

Has No closing tag

In the example you have used the attribute value to show the user a text and can recognize it

And the attribute onclick which is an event that allows the button to execute JavaScript code, in this case a warning to the user that the button has been pressed

Remaining as a result:


Submit the form

To create a button to submit the form to the attribute type we will assign the value submit

Has No closing tag

In the example you have used the attribute value to show the user a text and can recognize it

This example does not send anything to the server because you have not used the attributes action indicating the target URL or method indicating the GET or POST method

Remaining as a result:


We can also simulate the behavior of a submit button from an image

In the example you have used the attribute value to show the user a text and can recognize it

This example does not send anything to the server because you have not used the attributes action indicating the target URL or method indicating the GET or POST method

Remaining as a result:


Reset the form

To create a button to reset the form with the attribute type we will assign the value reset

Has No closing tag

In the example you have used the attribute value to show the user a text and can recognize it

Si escribimos algo en el cuadro de texto podremos comprobar que si pulsamos el botón reset el contenido del cuadro de texto vuelve a ser su valor por defecto

Remaining as a result:



Attach files

To create a button that allows to attach files to the attribute type we will assign the value file

This button will only be useful if we have chosen the POST method and have included at item form the attribute enctype=’multipart/form-data’

Además del botón aparece una etiqueta con el estado del archivo adjunto, que nos dirá si hay un archivo adjunto y en caso de haberlo su nombre y extensión

Pressing the button opens a system file explorer to the user, with which you can select the file you want to attach

Has No closing tag

In the example you attach a picture to the form, although it is not functional because it has not been added to the attribute action nor does it have a button to submit the form

You have used the attribute ok to tell the browser what MIME-types you may receive the browser when you press the button

In this case, you can only receive images of type jpeg and png

Remaining as a result:


Numbers

To create a box that can force the user to enter a number to the attribute type we will assign the value number

Has No closing tag

The example used the attributes:

  • min

    numeric value of minimum supports, the box

  • max

    maximum numeric value that supports the box

  • step

    controls the increase in numbers, if omitted, by default it is 1

  • value

    numeric value by default

Remaining as a result:


Ranges

To create a range of numbers that can force the user to enter an approximate number to the attribute type we will assign the value range

Has No closing tag

The example used the attributes:

  • min

    numeric value minimum that supports the range

  • max

    maximum numeric value that supports the range

  • step

    controls the increase in numbers, if omitted, by default it is 1

  • value

    numeric value by default

Remaining as a result:


Color palette

To assign a color from the palette to the attribute type we will assign the value color

Has No closing tag

In the example it has been used in the attribute value the default hexadecimal #FF0000

Remaining as a result:


Calendar

To assign a date from one calendar to the attribute type we will assign the value date

Has No closing tag

The example used the attributes:

  • min

    value of minimum date that supports the range of dates

  • max

    value of maximum date that supports the range of dates

  • step

    controls the increase in dates in the calendar, if omitted, by default it is 1

  • value

    date value by default

Keep in mind that the format for dates that are supported by the control is YYYY-MM-DD, es decir, A para un año con 4 dígitos, M para un mes de 2 dígitos y D para un día de 2 dígitos todos ellos separados con el símbolo –

Remaining as a result:


Hidden

Sometimes there is information that the developer does not want the user to be able to see, for this the hidden fields are used

These are fields that the user cannot see, but that are sent next to the form to the server

To assign hidden field to the attribute type we will assign the value hidden

Has No closing tag

The example sends three hidden fields giving the server information about the client, without that information appearing in the user's browser

Remaining as a result:




We shouldn't be able to see any of the hidden fields in the browser, but if we use our browser option View code, we can see that in fact, these fields exist

Text box multiple lines

It is similar to the text box but allows you to write more than a line to do this we will use the item textarea

In the example we can see that the most significant difference with respect to the text box is that we can use more than one line

In addition, we have specified with the attribute rows the number of rows to 4, with the attribute al the number of columns at 50 and with the attribute maxlength the maximum number of characters at 100

Remaining as a result:



Selection lists

The item select it serves to create a drop-down list selection

Its scheme is very similar to text boxes, although its contents cannot be modified, only selected

The elements option form the list and the server will be sent in value of your attribute value

In the example you have specified a list of selection of colors and it has set the color Green by default, using the reserved word selected

Remaining as a result:



Groupings of elements

The item fieldset serves to group related items together

In the example created a group to contain the user access control through login

It has been used the item legend that serves as a title or caption of the group

You have used the attribute required for the fields user and pass are mandatory and if we try to submit the form, the browser will show us an error message

The result is a box that contains all controls and has as its title Login for User

Remaining as a result:

Login for User



CSS

CSS

Cascading style sheets (CSS) are a graphic design language for defining and creating the presentation of a structured document written in a markup language, typically web pages written in HTML or XHTML; the language can be applied to any XML document, including XHTML, SVG, XUL, RSS, etc. It also allows you to apply non-visual styles, such as auditory style sheets

A style sheet is nothing more than a text file with a .css extension. Although style sheets were defined in the mid-1990s, they have had a special impact since their latest release (CSS3), in combination with HTML5

Different style sheets can be applied depending on the device on which we display our website (a large screen, a mobile, printed paper, etc)

Integration of styles in a page

There are several ways to integrate styles into a page. But normally we'll use one of these two:

  • Included as a label that is part of the HTML

    The problem with this option is pretty obvious. If in the future we would like to change the color of the paragraphs containing the text, we would have to search one by one for all occurrences and change them manually

  • Defined as a style rule in the header

    On a real web page we'll use more than one style rule, so it won't be a good option to add them one by one in the header

  • Defined with the label <link> to an external file

    Normally we will use more than one style rule, so it will be a good option to add them from an external .css extension file and link them in the HTML header with the tag <link>

Structure of a style sheet

A style sheet defines one or more rules that are applied to items that meet this rule

Each rule consists of two parts:

  • Selector: indicates which elements we're going to apply the rule to. More than one selector can be written for the same rule separated by commas
  • List of statements: the styles to apply to items that comply with the rule. They correspond to a couple property:value, separated by semicolons

The example defined a rule that applies to all paragraph p-elements in the HTML. In addition, the text has been set red, its font as Verdana, and its paragraph alignment is centered

Additionally, we can add comments, which will be written between /* and */

You can also add at directives (which start with a button), which change the way you apply the rules

DOM tree

The document object model (DOM) is the structured, tree-shaped representation of all elements written in an HTML document

For example, any HTML document starts with the tag , also containing the labels and , with their respective closing labels

On the other hand, within the header (label <head>) will in turn contain elements with labels <meta>, <link>, <title>, etc

And the body (label <body>), will in turn contain more elements and so on until it reaches its closing labels

The hierarchical structure resulting in computing is called a tree

Specifically, the tree that represents the structure of an HTML document is DOM

Thanks to this tree-shaped structure, we can uniquely identify each element of the HTML document, depending on how those elements are related to each other, we will be able to apply different style rules to them

The relationships we can identify are:

  • Descendants: are all elements contained (directly or indirectly) by an element

    For example, <head>, <meta> or <body> they are descendants of <html>

  • Direct Son: they are the descendants of first level

    For example, <head> he is the son of <html>

  • Brothers: descendants who have a common father

    For example, all the elements <meta> are brothers if

Thanks to these relationships within the DOM, in the example we used earlier that affected only the elements <p>, we could also apply it to the elements contained in a division <div> that contains a class or an id specific

Or we could create rules for siblings that share a node

By relying on the JavaScript language and the DOM, you can modify the content of the elements once the website is loaded into the browser

Cascading style

Thanks to DOM we can identify the specific elements of an HTML document, and therefore we can apply the style sheets

A style sheet can contain different rules that configure the same element, we can even have multiple style sheets with conflicting rules

In this example, our rules say that for every element of the <body>, including its descendants, will be applied to it the black background color and the red text color

In the following rule, we tell you that in the element <p> paragraph, the text must be blue

The final document will have all the black background color elements and the red text, but in addition the paragraphs will have blue

The rules have been applied to each other, in the form of a waterfall. That's why they are called Cascading style sheets (CSS)

In general, styles are inherited. First they set the property of the parent element and their descendants inherit them, to finally apply their own, which in turn are inherited by their descendants, until they reach the last descendant node of the style sheet

In the event that we have two elements that are brothers and there is conflict to see who inherits which property, the most specific one is applied and if they have the same properties, the last style defined will be applied

That is, if a rule is defined in two external style sheets, the sheet rule that was later included in the HTML document will be applied. That's why the order in which we include them is very important

First we will include the leaves, more general, and then those that are more specific

If you have embedded a rule in the HTML, the style that has been defined will be the one that will have the highest priority than the rule that is included in the HTML header

In short, the following priorities will apply when applying a rule to a particular item:

  1. Finds all the statements that apply to the item
  2. If there are no rules, the inherited value will be used

    If there is no inherited value, the browser will apply the default value

  3. If there are rules, the highest priority will be applied according to the following criteria:

    • A weight is assigned according to its origin: author, user or browser style sheet
    • Attributes with the !important keyword: will have higher priority
    • Specific selectors: will have higher priority
    • Two rules with the same priority: applies the indicated in last place

CSS Reset

Each browser has its own style sheet by default

This implies that the default style of some elements can be different for each browser

For this reason it is advisable to restart the styles applied to the elements by adding a special CSS (the CSS Reset) at the beginning of our web pages

There are multiple CSSs that perform this task (such as those used in frameworks Yahoo YUI, HTML5 BoilerPlate or Normalize), but one of the most popular is Eric Meyer considered as one of the gurus of the CSS

To add it you only have to save the file in the css folder contained in the root of your web site and define it with the tag <link> in the header of your HTML:

Selectors

Selectors

The selectors are used to identify the elements to which it will apply the format defined in the list of statements

There are different types of selectors that can be used to define CSS rules

Let's describe them from the most general to the most specific (from the point of view from lowest to highest priority)

Universal Selector

It is set to * and applies to all elements of the page:



The example has configured the margins and font of the text, which are usually some of the most commonly used rules

Tag Selector HTML

Indicates the style to be applied to an element or a specified tag

Its there's more than one, they'll be separated by commas



In the example, labels 1 to 5 of the title have been set, applying the font of the large text

As can be seen, we can do without < and > the label

Class Selector

Some HTML elements have the attribute class that indicates the classes to which the element belongs

This attribute allows us to treat that element "class" in a specific way, both in css style application and in its behavior programmatically with JavaScript

To apply the class selector, we'll use tag.class

In the example, we have configured the text in blue color for all the elements of the header class, because if we do not specify a label, the universal selector *

In the example you have set the text alignment centered only for the elements of the class header, which belong to the title tag <h1>

We must take special care not to leave spaces between the label, the point and the name of the class, since that space is significant, as we will see later

Selector id

Some HTML elements have the id attribute that indicates that this unique identifier it belongs to that particular element

To apply the identifier selector, we'll use tag#id

As with classes, it is very important to use the spaces

The example has set the background color of the text to yellow, in that paragraph that has the featured identifier

Selectors, descendant, and adjacent

These selectors allow you to select elements that are contained within other according to the structure of the DOM tree

This is where spaces take importance, because if we separate two selectors with a space, then we will be applying the rule to all descendants of the first selector

In the example you have set the text font as Verdana for all the elements <p> that they are descendants of the element <section> (remember that they can be descendants of any level, since that rule will be inherited)

Can be mixed interchangeably selectors descendants of a class or id

In the example, we have configured the text color as red for any element of the class error that is a descendant of the element

If instead of applying it to all descendants we want it to only apply to direct descendants (children), then we will use the >

In the example, we have configured the font of the text as Verdana only for the items <p> that are children of the element <section>

We can also select the sibling elements, that is, those that appear right after other elements, then we will use the symbol +

In the example, we have configured the indentation of the first paragraph that appears just after the title tag <h1>

Selectors of attributes

These selectors are used to select elements based on their attributes

There are four types:

  1. [attribute]: elements that have an attribute named attribute, regardless of its value
  2. [attribute=value]: elements that have an attribute named attribute with the specified value
  3. [attribute^=value]: elements that have an attribute named attribute and whose value starts with the specified value
  4. [attribute$=value]: elements that have an attribute named attribute and whose value ends with the specified value

In the example, we have set up a link that we want in a different color if it leads to a url with secure HTTP

Pseudo-classes

There are selectors special to specify elements that have certain properties

They are classes virtual, because they are not specified in HTML, but represent the positions or states in which an item can be found while viewing in the browser

The example has been configured to apply only if an item is the first child of its parent, for this we have used the first-child pseudoclass, only the first element <li> from a bullet list (<ul>) will appear in green

There are other pseudoclasses that will help us select a specific brother from among the children of an element:

  • :nth-child(n) : represents the n-th brother

    It allows you to include a more complex form such as:

    • :nth-child(even) : that represents the children who occupy positions pairs
    • :nth-child(odd) : that represents the children that occupy odd positions

    (for example to make odd rows in a table have different background color and have a hebrew effect on a table)

  • :nth-last-child(n) : similar to the previous one, but starting to count from the end

There are also dynamic pseudoclasses, which indicate the status of items when the user interacts with them:

  • :hover : is used to set the style when the user mouses over the element
  • :active : is used to set the style when the user click on the item or keep the mouse button pressed over it
  • :focus : is used to set the style when the element has focus

Pseudoclasses related to links are also very typical:

  • a:link : sets the style of the link when it has not yet visited or when the user has not already pressed
  • a:hover : set the style when the user places the mouse over the link element
  • a:active : set the style when the user clicks the link
  • a:visited : set the style when the user has already visited

The example has set the status of unvisited, visited or mouse-based links

When using this CSS, the links in the document will appear un underlined and green

By placing the mouse over them they will stop at blue and, once visited, they will turn red

Example of Selectors in action

In the following example has included an HTML page and several of the selectors explained above

You can check the result by viewing it yourself in your browser and if you don't use a CSS reset, you might have different results in other browsers

Now we show the contents of the exampleSelectors.css file

Positioning of elements

Positioning of elements

Positioning 'classic' elements is based on the model of blocks, which are placed to fill the page space from left to right and top to bottom

However, this model does not adapt well on mobile devices, where we will encounter problems with the size, orientation in the browser and even in the reordering of the elements to fit the type of device

To solve these problems appeared model of flexible positioning, which simplifies these tasks considerably

However, this model is too detailed to organize the overall structure of the website

For that reason, the model grid, which divides the space into a virtual grid and creates an array divided into cells within that grid, assigning the elements to a particular cell that will occupy so many additional cells depending on the size and orientation of the device

These two models are supported in addition to the so-called responsive design, which allows our website to adapt to the device on which it will be viewed: smartphones, tablets or desktop PCs

Model block

The boxes of the elements are placed by default following the 'normal flow', that is, pushing the boxes left and up

You can use the property position to modify the 'normal flow‘:

  • position: static it is the mode of positioning by default
    The box will occupy the position of the 'normal flow
  • position: relative using the properties top, right, bottom and left move your position
    These dimensions indicate the spacing that is left to each side in accordance with the original position of the box
    The rest of the boxes are not affected by this displacement, so they respect their reserved space
  • position: absolute it removes the box from the normal flow and placed the new box in a fixed position with respect to its containing box
    Supports the properties top, right, bottom and left
    You can overlap other elements because it is not respecting your space reserved
  • position: fixed similar to absolute positioning, but you specify the position relative to the window
    This implies that the box maintains its position and does not move when using the scroll bar
  • position: float the box is shifted to one side using the properties left or right, moving it to one end of the containing box or to the first floating box it finds in that direction
    May overlap with other elements that are not floating boxes
  • clear will only apply if there are floating boxes, for force the item to be displayed under the floating box of a certain type with the properties left or right; or anyone with both

Let's use this sample html to be able to check the use of the block model, for this we will use as a basis, the following sample style sheet:

A large font size was intentionally used to force scrolling. Now perform the following exercise so you can check for yourself how the block model works:

  1. Change the positioning of the block a a relative and asignale spacing top of 1em and a spacing left of 2em

    The blue block will overlap the red block, but the reserved space that should have occupied the blue block is preserved
  2. Change the positioning of the block c a relative and asignale spacing top of 1em and a spacing left of 2em

    The pink block will change its position relative to its container (the red block)
  3. Change the positioning of the block a a absolute and asignale spacing top of 1em and a spacing left of 2em

    The blue block will overlap the red block, but since no space has been reserved for the blue block, the red will be placed in the upper left corner
    And if we scroll, the blocks will no longer be visible
  4. Change the positioning of the block a a fixed and asignale spacing top of 1em and a spacing left of 2em

    The blue block will overlap the red block, but since no space has been reserved for the blue block, the red will be placed in the upper left corner
    And if we scroll, we will see that the blue block has been fixed in its position with respect to the window
  5. Change the positioning of the block a a float: right

    The blue block will overlap the other elements, have been placed on the right edge of the screen and no space has been reserved for that block
  6. Change the positioning of the block c a float: right

    The pink block will stick to the right side of your container, the red block
  7. Change the positioning of the block b a float: right

    The red block will stick to the right side of the previous floating element, the blue block
  8. Change the positioning of the block a a float: left and added to p the property clear: right

    The paragraph will be placed under the red block, but will overlap the blue block
  9. Change the positioning of p a clear: both

    The paragraph will be placed below the blue block

Flexible model

The flexible positioning allows you to accommodate the elements of the page according to changes in the dimensions and orentación of the page

It allows us to make a responsive design for our web pages you envisage properly in any device

This standard is relatively recent and is not yet supported by all browsers, but in the future it will be

As advantages you get a more readable and simple code, where you can change the order of the elements regardless of the order in the HTML code

The flexible model is appropriate for placing small components of a web page

To make a general arrangement of the elements of the page, the grid model is being imposed

The main idea is that a flexible container expands or compresses to fill the free space or to fit the available area

So we'll have a flex container and a series of flex item

To define a container, we will use the property display: lex (or display: kit-web.flex if we want Safari support)

All the elements will be elements flex

This model does not use concepts such as horizontal or vertical sorting, but defines a main axis and a secondary axis (cross axis)

This easily adjusts the design to the device's orientation changes

For each axis we can place the components at their start (main-start or cross-start) y final (main-end or cross-end)

Let's use this sample html to be able to check the use of the flexible model, for this we will use as a basis, the following sample style sheet:

Direction of the elements

The property flex-direction specifies the direction of the main axis, that is, how elements are placed inside the container

Supports the following values:

  • row
  • row-revese
  • column
  • column-reverse

To check its behavior, add the following CSS to the previous example:

Fit in the main shaft

The property wrap sets whether items need to be adjusted for display in a single row (or column)

Supports the following values:

  • nowrap adjust the elements to a line
  • wrap adjusts the items but without changing its size
  • wrap-reverse adjusts the elements but without resizing them, but in the reverse order of rows

To check its behavior, add the following HTML to the previous example:



And the following CSS:

Alignment of the content

With the property justify-content we can align the elements with respect to the main axis of the container

Allows us to decide what to do with the remaining space

Supports the following values:

  • flex-start board items at the beginning of the axis
  • flex-end board items at the end of the shaft
  • center centers the elements
  • space-between divides the space between the elements, leaving the ends attached to the edge
  • space-around all of the remaining space is distributed around each element

To check its behavior, add the following HTML to the previous example:



And the following CSS:

Fit on the secondary axis

To align the elements with respect to the secondary axis, we have the property align-items

Supports the following values:

  • strech to occupy all the width
  • flex-start aligns elements to the beginning of the axis
  • flex-end aligns items to the end of the shaft
  • center centers the elements

To check its behavior, add the following HTML to the previous example:

And the following CSS:

Properties of the elements

Up to now we have seen properties to configure the main container

Now let's list some very interesting properties to manipulate the elements:

  • order indicates the order in which they appear the element within the container
    In this way it will not be necessary to modify the HTML to reorder the elements, since we will do it by code
  • flex-grow sets the growth factor item
    That is, how it grows in relation to the other elements, as long as the container has free space
  • flex-shrink sets the factor of shrinkage item
    That is, how it decreases in relation to the other elements, as long as the container has free space
  • flex-basis indicates the default size (width) before the free space of the container is distributed
    Normally its default value is left: flex-basis: auto

There is a short form for the properties flex-grow, flex-shrink and flex-basis, simply specifying the value they will take: flex: 1 1 auto

To check its behavior, add the following HTML to the previous example:

And the following CSS:

Model grid

Although the box model flexible allows you to create sites adaptive thanks to the media queries, the model that is being imposed is the grid

In this model, the screen is divided into a grid is virtual, and the designer can choose how many cells of that grid will occupy each element depending on the device

This design has been popularized thanks to Bootstrap created by the developers of Twitter

In Bootstrap the available space is divided into 12 columns of equal size

For each item indicate how many columns will occupy depending on the size of the device

For example, for a sidebar we can indicate that it occupies 2 columns on a desktop, 6 columns (half the total width) for tablets and 12 columns (the entire width) on mobile devices

To achieve this, a set of classes will be used, in this example they would be: .col-md-2, .col-sm-6 and .col-xs-12

Sizes are defined in Bootstrap how to:

  • xs (extra small)
    Screens with width lower than 768px format
    The vast majority of smart phones
  • sm (small)
    Screens with a width less than 992px
    If the xs class has been defined and the size less than 768px, then that class will be applied
  • md (medium)
    Screens between 992px and 1200px
    This range represents the majority of desktop browsers
  • lg (large)
    Screens very big with a width over 1200px
    They are usually large high-definition screens

As you can see in the example, the content is organized into rows (row class) and within these rows we will create the columns with the desired sizes

Media Queries

A media query allows you to use the rules of style sheets depending on the characteristics of the medium (width, height and color)

They were added from CSS3, allow the presentation of the content to adapt to a specific scrape of output devices without having to change the contents and are the basis of adaptive design

They can be used in two ways: by importing a style sheet or by applying them within the same style sheet

Importing style sheets

We can use the media queries to choose different CSS depending on the medium or the characteristics of the same

Currently there are only two supported means:

  • screen a browser
  • print a printer

As can be seen in the example, defining the media type is as simple as adding the attribute media within the element link

It is also possible to indicate conditions about the media type, in the example we have told you to load when the media has a width less than 800px, so that you can use it with tablets

Rules @media

The rules @media allow us to indicate on what media type should apply certain CSS rules

Its generic sintasix is:

The only mediatype supported are screen and print, as we've seen before

As can be seen in the example, media feature allow us to indicate characteristics of the device, and you can add conditions by using logical operators and, not and only

We can using the media feature specify the size of the device, its temptation or resolution, number of colors, etc

Some of the highlights are:

  • aspect-ratio width/height of the device
  • min-aspect-ratio minimum width/height of the device
  • max-aspect-ratio maximum width/height of the device
  • color-index number of colors the device can display
  • width exact width
  • min-width minimum width
  • max-width maximum width
  • height high exact available
  • min-height minimum height available
  • max-height high maximum available
  • orientation orientation, supports values:
    • landscape
    • portrait

Adaptive layout with Media Queries

Let's see two examples with media queries to understand how to make our own adaptive designs, one with the flexible model and another with the model grid

Adaptive layout with the flexible model

In the following example, we create an adaptive layout with the flexible model is very easy

Because we can take advantage of the possibility to reorder the items on that offers us this option

Let's start from a 3-column layout with the navigation bar, the main content and a sidebar

When the size of the browser is less than 640px will go to a single column

The HTML we'll use in the example is as follows:

The CSS code in the flexible.css file that we'll use in the example is as follows:

Adaptive design with the model grid

In the following example, we create an adaptive layout with the model grid is very easy

One of the main limitations is that no longer that we can reorder the elements

We are going to use a grid of type Bootstrap

To do this we will use the classes cols-xs-12 to indicate that in small size the element will occupy 12 columns, col-sm-8 will occupy 8 columns for a small size and col-sm-2 will occupy 2 columns for a slightly larger size

For the change of size small to large has been assigned 768px format

The HTML we'll use in the example is as follows:

The CSS code in the grill.css file that we'll use in the example is as follows:

Lists of CSS declarations

Lists of CSS declarations

Properties are defined as lists of CSS declarations, they are very heterogeneous and cannot be applied to all HTML tags

We can find examples in w3schools or in MDN Web Docs Mozilla

Below we will address some of the main lists of statements

Units of measure

Many properties accept as the value of a unit of measure

En general, es recomendable utilizar medidas relativas en vez de absolutas

For example, for a web page we could indicate that we want 20 pixels high, however, if our users change devices, such as a mobile or a tablet, that size would be too large or the content would appear disproportionate.

To avoid that or similar problems, CSS declarations support the following units:

  • Percentage: sets the size in percent with respect to the inherited value
  • em: sets the size according to the current font (or the legacy font, if no font size is defined)
  • px: sets the size in pixels (a pixel represents a specific point on the screen that shows our page), being an absolute measure, as it can cause problems, we should limit its use to specific cases

We may use CSS declarations to indicate the visual appearance of the web page on different devices, such as a printer. For those cases we can use other types of measures:

  • cm, mm, in: the size is set to one of the international units (cm for centimeters, mm for millimeters, and in for inches)
  • pt: the size is set in points (one point equals \frac{1}{72} inch)

The use of relative measures (percentages or em) allow our page to be displayed correctly on any device. This practice is called design adaptive or responsive, that is, our design will adapt to the device on which it is viewed (a browser, a mobile, a tablet, etc.)

Colors

Another of the fundamental elements for a web page is the treatment of the colors

There is a list of 140 basic colors that we can find predefined, we can also define them manually using the RGB notation (Red, Green, Blue) to indicate the amount of red, green and blue that make up that color

To define the color we will use a value between 0 and 255 (in its value hexadecimal), starting the encoding with the '#' symbol followed by a 6 digit hexadecimal number

We can define color in the following ways:

  • color: value where value is one of the predefined colors
  • colour: code dónde código es un valor que empieza por el símbolo ‘#’ seguido de un número hexadecimal de 6 cifras
  • color: RGB(entero, entero, entero): dónde RGB es una función que admite 3 valores entre 0 y 255 que corresponden a la cantidad de rojo, verde y azul que componen ese color
  • color: RGB(entero%, entero%, entero%): igual que la anterior, pero el valor entero es un porcentaje
  • color: transparent: the color transparent is also a valid color in CSS3

Text properties

Las principales propiedades que se pueden utilizar en los elementos de texto son:

  • color

    indica el color de la fuente. Su valor es un color, ya lo hemos descrito en el previous paragraph

  • font-size

    representa el tamaño de la fuente, como ya se ha descrito en el previous paragraph it is recommended to use relative values

  • font-style

    admite un estilo de letra para el texto, podemos elegir entre uno de los siguientes estilos:

    • normal es el estilo por defecto del navegador, si no se especifica, se tomará este valor
    • italic it is the default style of the browser for the letter in italics
    • oblique es el estilo por defecto del navegador para la letra oblique, es similar a la cursiva, si la fuente no permite el tipo oblique tomará el estilo como italic
    • initial is used to set a CSS property to its default value
    • inherit is used to inherit a property value from its parent element
  • font-weight

    supports a bold font style for the text, we can choose between one of the following bold types:

    • normal is the default bold of the browser, if not specified, this value will be taken
    • bold defines the bold with bold
    • bolder defines the bold font with the characters more thick
    • lighter defines the bold with the characters thinner
    • integer define la negrita con un valor múltiplo de 100, con el valor 400 por defecto y el 700 para bold
    • initial is used to set a CSS property to its default value
    • inherit is used to inherit a property value from its parent element
  • text-decoration-line

    establece el tipo de decoración del texto para el subrayado, podemos elegir entre uno de los siguientes tipos de decoración:

    • none valor por defecto del navegador, si no se especifica, se tomará este valor
    • underline the underline will be below the text
    • overline the underline will be on the text
    • line-through the underscore will be through text
    • initial is used to set a CSS property to its default value
    • inherit is used to inherit a property value from its parent element
  • text-decoration-color

    establece el color para la decoración del texto, podemos elegir entre uno de los siguientes tipos de decoración:

    • color where color is one of the values seen in the previous paragraph
    • initial is used to set a CSS property to its default value
    • inherit is used to inherit a property value from its parent element
  • text-decoration-style

    establece el tipo de decoración del texto, podemos elegir entre uno de los siguientes tipos de decoración:

    • solid valor por defecto del navegador, si no se especifica, se tomará este valor. Mostrará la línea en una única línea
    • double show the line with a double line
    • dotted show the line as a dotted line
    • dashed show the line as a dashed line
    • wavy show the line as a wavy line
    • initial is used to set a CSS property to its default value
    • inherit is used to inherit a property value from its parent element
  • text-transform

    establece el texto en letras minúsculas o mayúsculas, podemos elegir entre uno de los siguientes tipos de transformación:

    • none valor por defecto del navegador, si no se especifica, se tomará este valor. No se tomarán letras mayúsculas
    • capitalize transforms the first letter of each word to uppercase
    • uppercase transform all letters to uppercase
    • lowercase transform all letters to lowercase
    • initial is used to set a CSS property to its default value
    • inherit is used to inherit a property value from its parent element
  • letter-spacing

    aumenta o disminuye el espacio entre caracteres en un texto, podemos elegir entre uno de los siguientes:

    • normal valor por defecto del navegador, si no se especifica, se tomará este valor. No hay espacios extra
    • length dónde lenghth es la cantidad de espacios extra entre caracteres (también están permitidos valores negativos)
    • initial is used to set a CSS property to its default value
    • inherit is used to inherit a property value from its parent element
    • word-spacing

      aumenta o disminuye el espacio entre las palabras en un texto, podemos elegir entre uno de los siguientes:

      • normal valor por defecto del navegador, si no se especifica, se tomará este valor
      • length dónde length es la cantidad de espacios extra entre palabras (también están permitidos valores negativos)
      • initial is used to set a CSS property to its default value
      • inherit is used to inherit a property value from its parent element
    • line-height

      especifica la altura de una línea, podemos elegir entre uno de los siguientes:

      • normal valor por defecto del navegador, si no se especifica, se tomará este valor
      • number where number is a value that will be multiplied by the current font size to set the height of the line
      • length dónde length es la altura para esa línea (también están permitidos valores negativos)
      • % is the height for that line, in percentage of the size of the current font
      • initial is used to set a CSS property to its default value
      • inherit is used to inherit a property value from its parent element
    • text-align

      especifica la alineación horizontal del texto en un elemento, podemos elegir entre uno de los siguientes:

      • left the text is aligned to the left
      • right the text is aligned to the right
      • center the text is aligned centered
      • justify el texto las líneas son estiradas para que cada línea tenga el mismo ancho (como en los periódicos y las revistas)
      • initial is used to set a CSS property to its default value
      • inherit is used to inherit a property value from its parent element
    • text-indent

      especifica la sangría de la primera línea en un bloque de texto, podemos elegir entre uno de los siguientes:

      • length dónde length es la sangría de la primera línea en un bloque de texto (también están permitidos valores negativos, en ese caso se usará una sangría a la izquierda)
      • % is the indentation of the first line in a block of text in percentage of the size of the parent element
      • initial is used to set a CSS property to its default value
      • inherit is used to inherit a property value from its parent element

    Es muy importante definir una fuente que sea coherente con el estilo de nuestra web. Para ello se dispone de la propiedad font-family, en la cual especificaremos la fuente (verdana, arial, time new roman, etc) que será usada para ese texto

    Sin embargo nos encontraremos con un problema si esa fuente en concreto no está definida en el navegador, por eso es recomendable especificar varias fuentes en caso de que no existiera alguna de ellas

    Another limitation is that we can only use sources that meet standards allowed by the browsers

    To solve problems related to the sources there are servers text sources they offer the possibility to load the font that we need of that server

    In the above example we have used one of the reference sources from Google called Roboto, and we have added to our header

    Background properties

    To set the background of an element we will use the property background-color

    Can also be used as a background image using the property background-image, que se repetirá vertical y horizontalmente para cubrir todo el elemento

    We may limit the way in which it repeats that image with the properties background-repeat: repeat-y and background-repeat: repeat-x

    In the example above we have used the property background-repeat: no-repeat para desactivar la repetición de la imagen, estableciendo además una posición fija, en la esquina inferior derecha, con la propiedad background-position: right bottom

    Para mantenerla fija y que haga scroll en la página, se ha utilizado la propiedad background-attachment: fixed

    Dimensions and edges

    To indicate the dimensions of an element, we use the properties width and height

    We have to take into account if their margins are internal or external

    To do this we first define the margin from the edge to the other elements with the property margin

    In the second place, we define the inner margin to the edge of the item with the property padding

    We can assign an outer margin to the four sides of the property margin or we can tell an outer margin, in particular, for each side using margin-top, margin-bottom, margin-left or margin-right

    De forma análoga, se puede realizar para los márgenes internos utilizando padding-top, padding-bottom, padding-left or padding-right

    Una vez difinidos los márgenes externos e internos, podremos configurar la apariencia que tomará el borde

    First we will establish the style with the property border-style, la cual admite los valores dotted, dashed, solid or double

    También es posible usar valores para crear bordes biselados, pero las guías de estilo modernas desaconsejan su uso por estar “pasados de moda”

    In the second place, we are able to customize the width of the stroke with the property border-width and your color with border-color

    Properties for lists

    Podemos utilizar las siguientes propiedades para manejar elementos lista:

    • list-style-type: representa el tipo de marcador que se utilizará en la lista
      Existen estos valores predefinidos:

      • circle
      • square
      • decimal
      • lower-roman
      • upper-roman
      • none
    • list-style-position: indica si el marcador se incluirá dentro del texto (propiedad inside) o fuera (propiedad outside), siendo esta última la más habitual
    • list-style-image: permite añadir una imagen como marcador
      We may use the values none or url(‘url de la imagen’)

    Other properties

    Además de las propiedades anteriores vamos a destacar un par más que nos serán de especial utilidad a la hora de dar formato a nuestros elementos:

    • visibility: indica si el elemento está visible o no
      Puede tomar uno de los siguientes valores:
      • visible: el elemento está visible
      • hidden: el elemento está no visible
      • collapse: solo podremos usarlo con los elementos de tablas para no visualizar una fila o una columna concreta
    • display: cambia el tipo de caja del elemento, puede tener los valores:
      • block
      • inline
      • none

Preprocessors CSS

Preprocessors CSS

El uso de procesadores CSS surge por un problema muy común en las hojas de estilo, muchos valores se repiten constantemente

Como podemos ver en el ejemplo anterior, el color #C0392B se repite constantemente en el código porque es nuestro color principal en este diseño

¿Pero, y si necesitamos cambiarlo? Esa situación nos obligaria a cambiar todas sus apariciones en la hoja de estilo

In the example above, it has solved the problem with the variable colorPrincipal, sin embargo, esta solución no es permitida por el CSS estándar

Therefore arises the need for the use of processors CSS, que son aplicaciones que permiten dotar al CSS de las ventajas de un lenguaje de programación, como el uso de variables, funciones, condiciones e incluso cálculos matemáticos, los cuales serán traducidos posteriomente a un CSS válido

No existe un estándar claro para este tipo de procesadores, pero tenemos las siguientes alternativas:

  • Sass funciona con Ruby, el cual viene preinstalado en Mac; si eres usuario de Windows necesitaras instalar previamente Ruby
    Funciona mediante línea de comandos en un terminal, ya que no tiene entorno gráfico
    Si quieres usarlo en modo visual, existen varias herramientas de pago que podrian interesarte
  • LESS está escrito en javascript, por lo que su instalación es tan sencilla como su importación directamente a nuestro documento HTML
    There are free tools that help to compile your files written in LESS, a CSS valid
    Aunque puede configurarse LESS para que haga el proceso de compilación ‘the flight‘, aunque no es recomendable porque consume tiempo de carga cada vez que recompila
  • Stylus necesitaremos instalar previamente Node.js, el cuál tiene su propio conjunto de repositorios que permite tener siempre la última versión estable del programa
    Funciona mediante línea de comandos en un terminal, ya que no tiene entorno gráfico
    Si quieres usarlo en modo visual, existen varias herramientas de pago que podrian interesarte

La sintaxis de estas herramientas es similar aunque hay pequeñas diferencias entre ellas, ya que como se ha dicho, no hay un estándar para preprocesadores CSS

LESS

Installation

With this tool we will create files .less where you keep our CSS rules improved

We'll include LESS in our HTML using the import Javascript and it will translate the file .less in a .valid css that will be loaded in the HTML page

Este tipo de instalación usada sólo en desarrollo es considerada ‘the flight‘ y llamada compilación, por motivos de eficiencia, en la página de producción, se añadirá el .css válido y ya traducido

Para poder realizar esta traducción ‘the flight‘ añadiremos las siguientes líneas en el head de nuestro HTML:

En el ejemplo nuestro fichero LESS se llama mystyle.less y le hemos indicado al navegador que es una hoja de estilos LESS con la referencia ‘stylesheet/less’

Despues hemos cargado la libreria Javascrip de LESS llamada less.js, que será la encargada de traducir el archivo mystyle.less al CSS válido y lo cargará en el HTML

Variables

Antes hemos visto un ejemplo para definir una variable para el color, en LESS se definen las variables con el símbolo @

Mixins

Mixins allow a CSS rule to inherit all the declarations of other

En el ejemplo anterior hemos hecho que los elementos p, ul y ol incluyan todas las declaraciones de .block y así nos ahorramos el tener que volver a escribirlas en cada aparición

Mixins also allow the use of parameters to configure them

En el ejemplo anterior hemos definido el mixin error donde el ancho de borde es configurable con la variable @wideBorder

Si no hay parámetros, su valor por defecto será 2px, como se ha indicado en su definición

.error-generic llama al mixin para heredar todas las declaraciones y, como no tiene parámetros toma su valor por defecto

.error-login llama al mixin pero esta vez, como tiene un parámetro toma el valor del mismo

Legacy code

A veces surge el problema de tener varios elementos con el mismo padre, con lo que nos vemos obligados a repetir en cada aparición referencias al padre

En el ejemplo anterior tenemos el problema comentado, section es el padre en la mayoría de los elementos de la hoja de estilo, a su vez nav es padre de varios de ellos, al igual que a

En el ejemplo anterior lo hemos solucionado escribiendo anidaciones de los hijos dentro de los elementos padre, así nos ahorramos repetir las referencias

Además permite usar el símbolo & para referirse al elemento padre inmediato dentro del elemento hijo

Functions for the color

The functions for the color to change the color at compile time

Son bastante útiles para crear degradados, oscurecer botones al pasar el ratón, etc

Operations

LESS allows mathematical operations

Como se puede ver en el ejemplo, no tiene muchas restricciones, ya que permite hacer cosas sin sentido como mezclar distintas unidades

Media queries

One of the problems of the media queries is that we can have different definitions of the same class in disintos points of the CSS file

Podemos anidar los media queries dentro de la misma clase, solucionando el problema del ejemplo anterior

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