Está en la página 1de 42

Unidad 6: Introducción a jQuery

6.1 Sobre el lenguaje

Conocimientos previos
Para iniciarse en el uso de esta biblioteca de javascript deberás tener los conocimientos
básicos de HTML y CSS. También deberías haber adquirido los conocimientos básicos
de javascript y su acceso al DOM; los tipos de datos y variables.

Qué es jQuery
jQuery es una biblioteca de javascript. Una biblioteca, o library, es un conjunto de
funciones que facilitan el uso de un lenguaje, simplificando la realización de tareas
complejas. Crear una animación avanzada, añadir efectos visuales, realizar consultas y
ofrecer resultados... todas ellas son tareas que se pueden realizar con javascript, pero
que utilizando determinadas bibliotecas simplificamos su desarrollo. Así pues, jQuery
no es un lenguaje de programación, sino un conjunto de funciones escritas en javascript
que simplifican la realización de determinadas tareas en este lenguaje.
Bibliotecas JavaScript. Estadísticas de uso. 2021

La biblioteca fue creada en agosto de 2006 por John Resig, momento en el que se
publicó su versión 1.0. En abril de 2013 se pasó a la versión 2.0 y tres años después, en
junio de 2016 se alcanzó la versión 3.0. La última versión publicada en el momento de
realización de este curso es la 3.5.1 que se lanzó el 4 de mayo de 2020.

En la actualidad su uso se ha generalizado de forma global. En la gráfica extraída


de W3Techs podemos comprobar cómo solo el 19.5% de los sitios web no emplean
ninguna biblioteca de javascript, mientras que el 77.3% usan jQuery, lo que supone el
96% de todos los sitios que emplean alguna biblioteca. Su éxito se explica porque
simplifica la modificación de los documentos HTML, el uso de eventos y desarrollo de
efectos visuales, así como la interacción mediante AJAX. Se distribuye bajo una
licencia libre —MIT— que permite su uso en proyectos de cualquier tipo, libres y
privados.

JQuery incluye las siguientes funciones:

o Selección de elementos del DOM simplificada.


o Interactividad y modificaciones del documento.
o Eventos.
o Modificación de las hojas de estilos con capacidad para manejar CSS3.
o Efectos y animaciones visuales.
o AJAX.
o Posibilidad de añadir extensiones.
o Detección de funcionalidades del navegador.
o Compatibilidad con todas las versiones de los navegadores Chrome, Edge,
Firefox y Safari; con Internet Explorer desde su versión 9, con Opera en su
versión actual; y con las versiones móviles de los navegadores Android desde la
versión 4.0 y Safari en iOS desde su versión 7.

La biblioteca se ofrece de dos formas: una versión para desarrollo, fácilmente


interpretable ya que se proporciona una lectura sencilla y comentarios aclaratorios en las
funciones; y otra versión para producción, para usarla en nuestro proyecto una vez está
terminado y disponible en Internet. Esta última versión, que emplea el sufijo .min, se
encuentra comprimida y sin comentarios ni caracteres superfluos para que su tamaño
sea el menor posible.

Además de su versión básica o core, también se distribuyen versiones optimizadas para


determinadas tareas: jQuery UI para el desarrollo de interfaces de usuario; jQuery
Mobile, optimizada para el desarrollo móvil; o jQuery color, que proporciona
animaciones y otras funciones útiles para el manejo de colores. 

Cómo se usa
Para comenzar a trabajar con jQuery tenemos varias posibilidades. Podemos descargar
alguna de las versiones que se ofrecen desde su página oficial jQuery.com; o podemos
enlazar la biblioteca desde una red de distribución de contenidos o CDN —Content
Delivery Network—. Este último método puede mejorar la navegación de los usuarios
de la web, al ofrecer el recurso, en este caso la biblioteca jQuery, desde un servidor más
próximo al visitante.

En el primer caso accederemos a la página de descarga de la biblioteca y guardaremos


en nuestro servidor la versión o versiones que vayamos a usar. Por ejemplo la versión
3.5.1 sin comprimir para desarrollo. Almacenaremos ese archivo en la carpeta de scripts
de nuestro proyecto, js es un buen nombre para la carpeta, y lo enlazaremos desde el
HTML:
<head>
<script type="text/javascript" defer src="js/jquery-3.5.1.js"></script>
</head>

Si, en cambio, optamos por usar una CDN para proporcionar la biblioteca, podemos
usar alguna de las siguientes:

La red de jQuery: https://code.jquery.com/. Solo debemos acceder al enlace y copiar el


correspondiente a la versión que deseemos usar; por ejemplo, la versión 3.5.1 core, sin
comprimir:
<head>
<script defer src="https://code.jquery.com/jquery-3.5.1.js"></script>
</head>
La red de Google: https://developers.google.com/speed/libraries#jquery. Aporta la
ventaja de que si lo has descargado ya desde ella, lo cual es muy probable porque
muchos sitios —incluidos los propios de Google— enlazan la biblioteca desde ahí, no
es necesaria su descarga de nuevo.
<head>
<script defer
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></scri
pt>
</head>

La red de Microsoft: https://docs.microsoft.com/en-
us/aspnet/ajax/cdn/overview#jQuery_Releases_on_the_CDN_0. 
<head>
<script defer src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-
3.5.1.js"></script>
</head>

Sea cual sea el método elegido, una vez cargada la biblioteca podemos incluir nuestros
scripts después de ella y comenzar a hacer uso de las funciones proporcionadas:
<head>
<script defer src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script defer src="js/miScript.js"></script>
</head>

En el caso de querer probar los scripts en CodePen, podemos configurar el servicio para
que agregue la biblioteca a nuestros proyectos. Solo hay que acceder a la configuración
de un pen y seleccionar la biblioteca jQuery en la sección «Add External Scripts/Pens».
Sintaxis básica
La sintaxis de jQuery está hecha a medida para facilitar la selección de elementos
HTML y realizar acciones sobre ellos. Una expresión jQuery se inicia siempre con la
llamada a la función jQuery(), que, para simplificar su uso, puede y suele hacerse
mediante el alias $(). Dentro de esa función se indica el selector —admite los
selectores CSS— y, a continuación de ella separada por un punto, la acción a realizar
sobre el/los elementos que coincidan con el selector:
$(selector).acción()

Por ejemplo, para ocultar —acción hide— todos los párrafos del documento se podría
emplear la expresión:
$("p").hide()

Se ha empleado el selector de etiquetas para acceder a todos los párrafos, pero podemos
incluir cualquier selector de CSS. Es muy interesante conocer los selectores CSS, ya
que podemos usar cualquiera de ellos para acceder a los componentes del documento:
$("p").hide() // Oculta todos los párrafos
$("nav li").hide() // Oculta los elementos de lista que se encuentren en un
<nav>

$(".oculto").hide() // Oculta los elementos de clase "oculto"

$("#img01").hide() // Oculta el elemento con id=img01

$(":disabled").hide() // Oculta los elementos que hayan adquirido la


seudoclase disabled

$(":checkbox").hide() // Oculta los elementos de tipo checkbox

$("[href$='.pdf']").hide() // Oculta los elementos con valor del atributo


href terminado en .pdf

Para asegurarnos de que el código no es ejecutado antes de que la página se haya


mostrado por completo, debemos incluir el código jQuery dentro de una función que se
ejecute cuando el documento esté disponible:
$(document).ready(function() {

// Código jQuery a ejecutar cuando el documento esté disponible.

});

Si lo hacemos de esta forma, no aseguramos de que los selectores tienen disponibles


todos los objetos del documento. jQuery también proporciona un método abreviado para
lograr lo mismo: que el código no se ejecute hasta que el documento esté
completamente disponible:
$(function(){

// Código jQuery a ejecutar cuando el documento esté disponible.

});

Reto
Haz un script que, usando jQuery, elimine las imágenes de la página:
<div>
<figure>
<img alt="Gilbert Stuart Williamstown Portrait of George Washington.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Gilbert_Stuart
_Williamstown_Portrait_of_George_Washington.jpg/160px-
Gilbert_Stuart_Williamstown_Portrait_of_George_Washington.jpg" width="160"
height="194">
<figcaption>George Washington</figcaption>
</figure>
<p>The <a href="/wiki/President_of_the_United_States" title="President of the
United States">president of the United States</a> is the <a
href="/wiki/Head_of_state" title="Head of state">head of state</a> and <a
href="/wiki/Head_of_government" title="Head of government">head of
government</a> of the <a href="/wiki/United_States" title="United
States">United States</a>, <a href="/wiki/Indirectly_elected" class="mw-
redirect" title="Indirectly elected">indirectly elected</a> to a four-year <a
href="/wiki/Term_of_office" title="Term of office">term</a> by the American
people through the <a href="/wiki/United_States_Electoral_College"
title="United States Electoral College">Electoral College</a>. The
officeholder leads the <a href="/wiki/Executive_(government)"
title="Executive (government)">executive branch</a> of the <a
href="/wiki/Federal_government_of_the_United_States" title="Federal
government of the United States">federal government</a> and is the <a
href="/wiki/Commander-in-chief" title="Commander-in-chief">commander-in-
chief</a> of the <a href="/wiki/United_States_Armed_Forces" title="United
States Armed Forces">United States Armed Forces</a>.
</p>

<figure>
<img alt="Grover Cleveland - NARA - 518139 (cropped).jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Grover_Clevela
nd_-_NARA_-_518139_%28cropped%29.jpg/160px-Grover_Cleveland_-_NARA_-_518139_
%28cropped%29.jpg" width="160" height="206">
<figcaption>Grover Cleveland</figcaption>
</figure>
<p>Since the office was established in 1789, there have been 45 presidencies,
while 44 men have served as president. The first, <a
href="/wiki/George_Washington" title="George Washington">George
Washington</a>, won a unanimous vote of the Electoral College. <a
href="/wiki/Grover_Cleveland" title="Grover Cleveland">Grover Cleveland</a>
served two non-consecutive terms (the only president to have done so) and is
therefore counted as the 22nd and 24th president of the United States.
</p>

<figure><img alt="George H. W. Bush presidential portrait (cropped).jpg"


src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ee/George_H._W._B
ush_presidential_portrait_%28cropped%29.jpg/160px-
George_H._W._Bush_presidential_portrait_%28cropped%29.jpg" width="160"
height="210">
<figcaption>George H. W. Bush</figcaption>
</figure>
<p>There are four <a href="/wiki/Living_presidents_of_the_United_States"
title="Living presidents of the United States">living former presidents</a>.
The most recent to die was <a href="/wiki/George_H._W._Bush" title="George H.
W. Bush">George H. W. Bush</a>, <a
href="/wiki/Death_and_state_funeral_of_George_H._W._Bush" title="Death and
state funeral of George H. W. Bush">on November 30, 2018</a>.
</p>

<figure>
<img alt="William Henry Harrison daguerreotype edit.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/William_Henry_
Harrison_daguerreotype_edit.jpg/160px-
William_Henry_Harrison_daguerreotype_edit.jpg" width="160" height="190">
<figcaption>William Henry Harrison</figcaption>
</figure>
<p>The presidency of <a href="/wiki/William_Henry_Harrison" title="William
Henry Harrison">William Henry Harrison</a>, who died 31 days after taking
office in 1841, was the shortest in American history. <a
href="/wiki/Franklin_D._Roosevelt" title="Franklin D. Roosevelt">Franklin D.
Roosevelt</a> served the longest, over twelve years, before dying early in
his fourth term in 1945. He is the only U.S. president to have served more
than two terms. Since the ratification of the <a href="/wiki/Twenty-
second_Amendment_to_the_United_States_Constitution" title="Twenty-second
Amendment to the United States Constitution">Twenty-second Amendment to the
United States Constitution</a> in 1951, no person may be elected president
more than twice, and no one who has served more than two years of a term to
which someone else was elected may be elected more than once.<sup
id="cite_ref-1" class="reference"><a href="#cite_note-1">[1]</a></sup>
</p>

<figure>
<img alt="Zachary Taylor restored and cropped.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Zachary_Taylor
_restored_and_cropped.jpg/160px-Zachary_Taylor_restored_and_cropped.jpg"
width="160" height="210">
<figcaption>Zachary Taylor</figcaption>
</figure>
<p>Of those who have served as the nation's president, four died in office of
natural causes (William Henry Harrison, <a href="/wiki/Zachary_Taylor"
title="Zachary Taylor">Zachary Taylor</a>, <a href="/wiki/Warren_G._Harding"
title="Warren G. Harding">Warren G. Harding</a>, and Franklin D. Roosevelt),
four were <a
href="/wiki/List_of_United_States_presidential_assassination_attempts_and_plo
ts" title="List of United States presidential assassination attempts and
plots">assassinated</a> (<a href="/wiki/Abraham_Lincoln" title="Abraham
Lincoln">Abraham Lincoln</a>, <a href="/wiki/James_A._Garfield" title="James
A. Garfield">James A. Garfield</a>, <a href="/wiki/William_McKinley"
title="William McKinley">William McKinley</a> and <a
href="/wiki/John_F._Kennedy" title="John F. Kennedy">John F. Kennedy</a>),
and one resigned (<a href="/wiki/Richard_Nixon" title="Richard Nixon">Richard
Nixon</a>, facing <a href="/wiki/Impeachment_process_against_Richard_Nixon"
title="Impeachment process against Richard Nixon">impeachment</a>). <a
href="/wiki/John_Tyler" title="John Tyler">John Tyler</a> was the first vice
president to assume the presidency during a presidential term, and set the
precedent that a vice president who does so becomes the fully functioning
president with his presidency, as opposed to a <a
href="/wiki/Caretaker_president" class="mw-redirect" title="Caretaker
president">caretaker president</a>. The <a href="/wiki/Twenty-
fifth_Amendment_to_the_United_States_Constitution" title="Twenty-fifth
Amendment to the United States Constitution">Twenty-fifth Amendment</a> to
the Constitution put Tyler's precedent into law in 1967. It also established
a mechanism by which an intra-term vacancy in the vice presidency could be
filled. Richard Nixon was the first president to fill a vacancy under this
provision when he <a
href="/wiki/1973_United_States_vice_presidential_confirmation" title="1973
United States vice presidential confirmation">selected</a> <a
href="/wiki/Gerald_Ford" title="Gerald Ford">Gerald Ford</a> for the office
following <a href="/wiki/Spiro_Agnew" title="Spiro Agnew">Spiro Agnew</a>'s
resignation in 1973. The following year, Ford became the second to do so when
he <a href="/wiki/1974_United_States_vice_presidential_confirmation"
title="1974 United States vice presidential confirmation">chose</a> <a
href="/wiki/Nelson_Rockefeller" title="Nelson Rockefeller">Nelson
Rockefeller</a> to succeed him after he acceded to the presidency. As no
mechanism existed for filling an intra-term vacancy in the vice presidency
before 1967, the office was left vacant until filled through the next ensuing
presidential election and subsequent inauguration.
</p>

<figure>
<img alt="Thomas Jefferson by Rembrandt Peale, 1800.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Thomas_Jeffers
on_by_Rembrandt_Peale%2C_1800.jpg/160px-Thomas_Jefferson_by_Rembrandt_Peale
%2C_1800.jpg" width="160" height="191">
<figcaption>Thomas Jefferson</figcaption>
</figure>
<p>Throughout most of its history, <a href="/wiki/American_politics"
class="mw-redirect" title="American politics">American politics</a> has been
dominated by <a href="/wiki/Political_parties_in_the_United_States"
title="Political parties in the United States">political parties</a>. The
Constitution is silent on the issue of political parties, and at the time it
came into force in 1789, no organized parties existed. Soon after the <a
href="/wiki/1st_United_States_Congress" title="1st United States
Congress">1st Congress</a> convened, factions began rallying around dominant
<a href="/wiki/Presidency_of_George_Washington" title="Presidency of George
Washington">Washington administration</a> officials, such as <a
href="/wiki/Alexander_Hamilton" title="Alexander Hamilton">Alexander
Hamilton</a> and <a href="/wiki/Thomas_Jefferson" title="Thomas
Jefferson">Thomas Jefferson</a>. Greatly concerned about the capacity of
political parties to destroy the fragile unity holding the nation together,
Washington remained unaffiliated with any political faction or party
throughout his eight-year presidency. He was, and remains, the only U.S.
president never affiliated with a political party.<sup id="cite_ref-2"
class="reference"><a href="#cite_note-2">[2]</a></sup>
</p>
</div>

figure{
width:160px;
}
figcaption{
text-align:center;
}
figure:nth-of-type(2n){
clear:right;
float:right;
}
figure:nth-of-type(2n+1){
clear:left;
float:left;
}
Lo primero que debemos hacer, si vamos a usar expresiones de jQuery en
CodePen, es enlazar la biblioteca en la configuración del pen:

Ahora podemos comenzar a escribir el código. Para que se ejecute cuando


esté cargada la página, nos acostumbraremos a incluirlo en la función $
(function(){});
$(function(){
$("img").hide();
});
Como podemos comprobar, el código anterior elimina las imágenes, pero
mantiene los elementos figure, junto con su título. Obtenemos un mejor
resultado si eliminamos estos elementos:
$(function(){
$("figure").hide();
});

<div>
<figure>
<img alt="Gilbert Stuart Williamstown Portrait of George Washington.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Gilbert_Stuart
_Williamstown_Portrait_of_George_Washington.jpg/160px-
Gilbert_Stuart_Williamstown_Portrait_of_George_Washington.jpg" width="160"
height="194">
<figcaption>George Washington</figcaption>
</figure>
<p>The <a href="/wiki/President_of_the_United_States" title="President of the
United States">president of the United States</a> is the <a
href="/wiki/Head_of_state" title="Head of state">head of state</a> and <a
href="/wiki/Head_of_government" title="Head of government">head of
government</a> of the <a href="/wiki/United_States" title="United
States">United States</a>, <a href="/wiki/Indirectly_elected" class="mw-
redirect" title="Indirectly elected">indirectly elected</a> to a four-year <a
href="/wiki/Term_of_office" title="Term of office">term</a> by the American
people through the <a href="/wiki/United_States_Electoral_College"
title="United States Electoral College">Electoral College</a>. The
officeholder leads the <a href="/wiki/Executive_(government)"
title="Executive (government)">executive branch</a> of the <a
href="/wiki/Federal_government_of_the_United_States" title="Federal
government of the United States">federal government</a> and is the <a
href="/wiki/Commander-in-chief" title="Commander-in-chief">commander-in-
chief</a> of the <a href="/wiki/United_States_Armed_Forces" title="United
States Armed Forces">United States Armed Forces</a>.
</p>

<figure>
<img alt="Grover Cleveland - NARA - 518139 (cropped).jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Grover_Clevela
nd_-_NARA_-_518139_%28cropped%29.jpg/160px-Grover_Cleveland_-_NARA_-_518139_
%28cropped%29.jpg" width="160" height="206">
<figcaption>Grover Cleveland</figcaption>
</figure>
<p>Since the office was established in 1789, there have been 45 presidencies,
while 44 men have served as president. The first, <a
href="/wiki/George_Washington" title="George Washington">George
Washington</a>, won a unanimous vote of the Electoral College. <a
href="/wiki/Grover_Cleveland" title="Grover Cleveland">Grover Cleveland</a>
served two non-consecutive terms (the only president to have done so) and is
therefore counted as the 22nd and 24th president of the United States.
</p>

<figure><img alt="George H. W. Bush presidential portrait (cropped).jpg"


src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ee/George_H._W._B
ush_presidential_portrait_%28cropped%29.jpg/160px-
George_H._W._Bush_presidential_portrait_%28cropped%29.jpg" width="160"
height="210">
<figcaption>George H. W. Bush</figcaption>
</figure>
<p>There are four <a href="/wiki/Living_presidents_of_the_United_States"
title="Living presidents of the United States">living former presidents</a>.
The most recent to die was <a href="/wiki/George_H._W._Bush" title="George H.
W. Bush">George H. W. Bush</a>, <a
href="/wiki/Death_and_state_funeral_of_George_H._W._Bush" title="Death and
state funeral of George H. W. Bush">on November 30, 2018</a>.
</p>

<figure>
<img alt="William Henry Harrison daguerreotype edit.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/William_Henry_
Harrison_daguerreotype_edit.jpg/160px-
William_Henry_Harrison_daguerreotype_edit.jpg" width="160" height="190">
<figcaption>William Henry Harrison</figcaption>
</figure>
<p>The presidency of <a href="/wiki/William_Henry_Harrison" title="William
Henry Harrison">William Henry Harrison</a>, who died 31 days after taking
office in 1841, was the shortest in American history. <a
href="/wiki/Franklin_D._Roosevelt" title="Franklin D. Roosevelt">Franklin D.
Roosevelt</a> served the longest, over twelve years, before dying early in
his fourth term in 1945. He is the only U.S. president to have served more
than two terms. Since the ratification of the <a href="/wiki/Twenty-
second_Amendment_to_the_United_States_Constitution" title="Twenty-second
Amendment to the United States Constitution">Twenty-second Amendment to the
United States Constitution</a> in 1951, no person may be elected president
more than twice, and no one who has served more than two years of a term to
which someone else was elected may be elected more than once.<sup
id="cite_ref-1" class="reference"><a href="#cite_note-1">[1]</a></sup>
</p>

<figure>
<img alt="Zachary Taylor restored and cropped.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Zachary_Taylor
_restored_and_cropped.jpg/160px-Zachary_Taylor_restored_and_cropped.jpg"
width="160" height="210">
<figcaption>Zachary Taylor</figcaption>
</figure>
<p>Of those who have served as the nation's president, four died in office of
natural causes (William Henry Harrison, <a href="/wiki/Zachary_Taylor"
title="Zachary Taylor">Zachary Taylor</a>, <a href="/wiki/Warren_G._Harding"
title="Warren G. Harding">Warren G. Harding</a>, and Franklin D. Roosevelt),
four were <a
href="/wiki/List_of_United_States_presidential_assassination_attempts_and_plo
ts" title="List of United States presidential assassination attempts and
plots">assassinated</a> (<a href="/wiki/Abraham_Lincoln" title="Abraham
Lincoln">Abraham Lincoln</a>, <a href="/wiki/James_A._Garfield" title="James
A. Garfield">James A. Garfield</a>, <a href="/wiki/William_McKinley"
title="William McKinley">William McKinley</a> and <a
href="/wiki/John_F._Kennedy" title="John F. Kennedy">John F. Kennedy</a>),
and one resigned (<a href="/wiki/Richard_Nixon" title="Richard Nixon">Richard
Nixon</a>, facing <a href="/wiki/Impeachment_process_against_Richard_Nixon"
title="Impeachment process against Richard Nixon">impeachment</a>). <a
href="/wiki/John_Tyler" title="John Tyler">John Tyler</a> was the first vice
president to assume the presidency during a presidential term, and set the
precedent that a vice president who does so becomes the fully functioning
president with his presidency, as opposed to a <a
href="/wiki/Caretaker_president" class="mw-redirect" title="Caretaker
president">caretaker president</a>. The <a href="/wiki/Twenty-
fifth_Amendment_to_the_United_States_Constitution" title="Twenty-fifth
Amendment to the United States Constitution">Twenty-fifth Amendment</a> to
the Constitution put Tyler's precedent into law in 1967. It also established
a mechanism by which an intra-term vacancy in the vice presidency could be
filled. Richard Nixon was the first president to fill a vacancy under this
provision when he <a
href="/wiki/1973_United_States_vice_presidential_confirmation" title="1973
United States vice presidential confirmation">selected</a> <a
href="/wiki/Gerald_Ford" title="Gerald Ford">Gerald Ford</a> for the office
following <a href="/wiki/Spiro_Agnew" title="Spiro Agnew">Spiro Agnew</a>'s
resignation in 1973. The following year, Ford became the second to do so when
he <a href="/wiki/1974_United_States_vice_presidential_confirmation"
title="1974 United States vice presidential confirmation">chose</a> <a
href="/wiki/Nelson_Rockefeller" title="Nelson Rockefeller">Nelson
Rockefeller</a> to succeed him after he acceded to the presidency. As no
mechanism existed for filling an intra-term vacancy in the vice presidency
before 1967, the office was left vacant until filled through the next ensuing
presidential election and subsequent inauguration.
</p>

<figure>
<img alt="Thomas Jefferson by Rembrandt Peale, 1800.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Thomas_Jeffers
on_by_Rembrandt_Peale%2C_1800.jpg/160px-Thomas_Jefferson_by_Rembrandt_Peale
%2C_1800.jpg" width="160" height="191">
<figcaption>Thomas Jefferson</figcaption>
</figure>
<p>Throughout most of its history, <a href="/wiki/American_politics"
class="mw-redirect" title="American politics">American politics</a> has been
dominated by <a href="/wiki/Political_parties_in_the_United_States"
title="Political parties in the United States">political parties</a>. The
Constitution is silent on the issue of political parties, and at the time it
came into force in 1789, no organized parties existed. Soon after the <a
href="/wiki/1st_United_States_Congress" title="1st United States
Congress">1st Congress</a> convened, factions began rallying around dominant
<a href="/wiki/Presidency_of_George_Washington" title="Presidency of George
Washington">Washington administration</a> officials, such as <a
href="/wiki/Alexander_Hamilton" title="Alexander Hamilton">Alexander
Hamilton</a> and <a href="/wiki/Thomas_Jefferson" title="Thomas
Jefferson">Thomas Jefferson</a>. Greatly concerned about the capacity of
political parties to destroy the fragile unity holding the nation together,
Washington remained unaffiliated with any political faction or party
throughout his eight-year presidency. He was, and remains, the only U.S.
president never affiliated with a political party.<sup id="cite_ref-2"
class="reference"><a href="#cite_note-2">[2]</a></sup>
</p>
</div>

figure{
width:160px;
}
figcaption{
text-align:center;
}
figure:nth-of-type(2n){
clear:right;
float:right;
}
figure:nth-of-type(2n+1){
clear:left;
float:left;
}

$(function(){
$("figure").hide();
});

6.2 Eventos y acciones

Conocimientos previos
Es necesario tener una base de conocimientos de javascript sobre variables, eventos y
funciones para adentrarse en las herramientas  que proporciona jQuery. Para hacer
scripts con cierta complejidad también son necesarios los conocimientos generales de
cualquier lenguaje de programación sobre estructuras de control condicionales e
iterativas. 

Eventos
La base de la interactividad en la web son los eventos: acciones del usuario detectadas
por el navegador y que suelen actual como desencadenantes para la ejecución de
funciones. Hacer clic con un botón del ratón, pulsar una tecla en el teclado, introducir
un valor en un control de formulario o maximizar la ventana del navegador; son
acciones que jQuery puede capturar, lo que las convierte en eventos.

La forma de usarlos en jQuery es muy simple: Se asocia el evento que esperamos al


elemento deseado, pasándole la función a ejecutar. En el siguiente ejemplo ocultamos
las imágenes al hacer clic en un elemento al que le hemos dado la clase 'boton':
$(function(){
$(".boton").click(function(){
$("figure").hide();
});
});

<div>
<button class="boton">Eliminar imágenes</button>
<figure>
<img alt="Gilbert Stuart Williamstown Portrait of George Washington.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Gilbert_Stuart
_Williamstown_Portrait_of_George_Washington.jpg/160px-
Gilbert_Stuart_Williamstown_Portrait_of_George_Washington.jpg" width="160"
height="194">
<figcaption>George Washington</figcaption>
</figure>
<p>The <a href="/wiki/President_of_the_United_States" title="President of the
United States">president of the United States</a> is the <a
href="/wiki/Head_of_state" title="Head of state">head of state</a> and <a
href="/wiki/Head_of_government" title="Head of government">head of
government</a> of the <a href="/wiki/United_States" title="United
States">United States</a>, <a href="/wiki/Indirectly_elected" class="mw-
redirect" title="Indirectly elected">indirectly elected</a> to a four-year <a
href="/wiki/Term_of_office" title="Term of office">term</a> by the American
people through the <a href="/wiki/United_States_Electoral_College"
title="United States Electoral College">Electoral College</a>. The
officeholder leads the <a href="/wiki/Executive_(government)"
title="Executive (government)">executive branch</a> of the <a
href="/wiki/Federal_government_of_the_United_States" title="Federal
government of the United States">federal government</a> and is the <a
href="/wiki/Commander-in-chief" title="Commander-in-chief">commander-in-
chief</a> of the <a href="/wiki/United_States_Armed_Forces" title="United
States Armed Forces">United States Armed Forces</a>.
</p>

<figure>
<img alt="Grover Cleveland - NARA - 518139 (cropped).jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Grover_Clevela
nd_-_NARA_-_518139_%28cropped%29.jpg/160px-Grover_Cleveland_-_NARA_-_518139_
%28cropped%29.jpg" width="160" height="206">
<figcaption>Grover Cleveland</figcaption>
</figure>
<p>Since the office was established in 1789, there have been 45 presidencies,
while 44 men have served as president. The first, <a
href="/wiki/George_Washington" title="George Washington">George
Washington</a>, won a unanimous vote of the Electoral College. <a
href="/wiki/Grover_Cleveland" title="Grover Cleveland">Grover Cleveland</a>
served two non-consecutive terms (the only president to have done so) and is
therefore counted as the 22nd and 24th president of the United States.
</p>
<figure><img alt="George H. W. Bush presidential portrait (cropped).jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ee/George_H._W._B
ush_presidential_portrait_%28cropped%29.jpg/160px-
George_H._W._Bush_presidential_portrait_%28cropped%29.jpg" width="160"
height="210">
<figcaption>George H. W. Bush</figcaption>
</figure>
<p>There are four <a href="/wiki/Living_presidents_of_the_United_States"
title="Living presidents of the United States">living former presidents</a>.
The most recent to die was <a href="/wiki/George_H._W._Bush" title="George H.
W. Bush">George H. W. Bush</a>, <a
href="/wiki/Death_and_state_funeral_of_George_H._W._Bush" title="Death and
state funeral of George H. W. Bush">on November 30, 2018</a>.
</p>

<figure>
<img alt="William Henry Harrison daguerreotype edit.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/William_Henry_
Harrison_daguerreotype_edit.jpg/160px-
William_Henry_Harrison_daguerreotype_edit.jpg" width="160" height="190">
<figcaption>William Henry Harrison</figcaption>
</figure>
<p>The presidency of <a href="/wiki/William_Henry_Harrison" title="William
Henry Harrison">William Henry Harrison</a>, who died 31 days after taking
office in 1841, was the shortest in American history. <a
href="/wiki/Franklin_D._Roosevelt" title="Franklin D. Roosevelt">Franklin D.
Roosevelt</a> served the longest, over twelve years, before dying early in
his fourth term in 1945. He is the only U.S. president to have served more
than two terms. Since the ratification of the <a href="/wiki/Twenty-
second_Amendment_to_the_United_States_Constitution" title="Twenty-second
Amendment to the United States Constitution">Twenty-second Amendment to the
United States Constitution</a> in 1951, no person may be elected president
more than twice, and no one who has served more than two years of a term to
which someone else was elected may be elected more than once.<sup
id="cite_ref-1" class="reference"><a href="#cite_note-1">[1]</a></sup>
</p>

<figure>
<img alt="Zachary Taylor restored and cropped.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Zachary_Taylor
_restored_and_cropped.jpg/160px-Zachary_Taylor_restored_and_cropped.jpg"
width="160" height="210">
<figcaption>Zachary Taylor</figcaption>
</figure>
<p>Of those who have served as the nation's president, four died in office of
natural causes (William Henry Harrison, <a href="/wiki/Zachary_Taylor"
title="Zachary Taylor">Zachary Taylor</a>, <a href="/wiki/Warren_G._Harding"
title="Warren G. Harding">Warren G. Harding</a>, and Franklin D. Roosevelt),
four were <a
href="/wiki/List_of_United_States_presidential_assassination_attempts_and_plo
ts" title="List of United States presidential assassination attempts and
plots">assassinated</a> (<a href="/wiki/Abraham_Lincoln" title="Abraham
Lincoln">Abraham Lincoln</a>, <a href="/wiki/James_A._Garfield" title="James
A. Garfield">James A. Garfield</a>, <a href="/wiki/William_McKinley"
title="William McKinley">William McKinley</a> and <a
href="/wiki/John_F._Kennedy" title="John F. Kennedy">John F. Kennedy</a>),
and one resigned (<a href="/wiki/Richard_Nixon" title="Richard Nixon">Richard
Nixon</a>, facing <a href="/wiki/Impeachment_process_against_Richard_Nixon"
title="Impeachment process against Richard Nixon">impeachment</a>). <a
href="/wiki/John_Tyler" title="John Tyler">John Tyler</a> was the first vice
president to assume the presidency during a presidential term, and set the
precedent that a vice president who does so becomes the fully functioning
president with his presidency, as opposed to a <a
href="/wiki/Caretaker_president" class="mw-redirect" title="Caretaker
president">caretaker president</a>. The <a href="/wiki/Twenty-
fifth_Amendment_to_the_United_States_Constitution" title="Twenty-fifth
Amendment to the United States Constitution">Twenty-fifth Amendment</a> to
the Constitution put Tyler's precedent into law in 1967. It also established
a mechanism by which an intra-term vacancy in the vice presidency could be
filled. Richard Nixon was the first president to fill a vacancy under this
provision when he <a
href="/wiki/1973_United_States_vice_presidential_confirmation" title="1973
United States vice presidential confirmation">selected</a> <a
href="/wiki/Gerald_Ford" title="Gerald Ford">Gerald Ford</a> for the office
following <a href="/wiki/Spiro_Agnew" title="Spiro Agnew">Spiro Agnew</a>'s
resignation in 1973. The following year, Ford became the second to do so when
he <a href="/wiki/1974_United_States_vice_presidential_confirmation"
title="1974 United States vice presidential confirmation">chose</a> <a
href="/wiki/Nelson_Rockefeller" title="Nelson Rockefeller">Nelson
Rockefeller</a> to succeed him after he acceded to the presidency. As no
mechanism existed for filling an intra-term vacancy in the vice presidency
before 1967, the office was left vacant until filled through the next ensuing
presidential election and subsequent inauguration.
</p>

<figure>
<img alt="Thomas Jefferson by Rembrandt Peale, 1800.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Thomas_Jeffers
on_by_Rembrandt_Peale%2C_1800.jpg/160px-Thomas_Jefferson_by_Rembrandt_Peale
%2C_1800.jpg" width="160" height="191">
<figcaption>Thomas Jefferson</figcaption>
</figure>
<p>Throughout most of its history, <a href="/wiki/American_politics"
class="mw-redirect" title="American politics">American politics</a> has been
dominated by <a href="/wiki/Political_parties_in_the_United_States"
title="Political parties in the United States">political parties</a>. The
Constitution is silent on the issue of political parties, and at the time it
came into force in 1789, no organized parties existed. Soon after the <a
href="/wiki/1st_United_States_Congress" title="1st United States
Congress">1st Congress</a> convened, factions began rallying around dominant
<a href="/wiki/Presidency_of_George_Washington" title="Presidency of George
Washington">Washington administration</a> officials, such as <a
href="/wiki/Alexander_Hamilton" title="Alexander Hamilton">Alexander
Hamilton</a> and <a href="/wiki/Thomas_Jefferson" title="Thomas
Jefferson">Thomas Jefferson</a>. Greatly concerned about the capacity of
political parties to destroy the fragile unity holding the nation together,
Washington remained unaffiliated with any political faction or party
throughout his eight-year presidency. He was, and remains, the only U.S.
president never affiliated with a political party.<sup id="cite_ref-2"
class="reference"><a href="#cite_note-2">[2]</a></sup>
</p>
</div>
button{
width:100%;
padding:1em 0;
cursor:pointer;
background-color:#ef9a9a;
}
figure{
width:160px;
}
figcaption{
text-align:center;
}
figure:nth-of-type(2n){
clear:right;
float:right;
}
figure:nth-of-type(2n+1){
clear:left;
float:left;
}

$(function(){
$(".boton").click(function(){
$("figure").hide();
});
});

Uno de los métodos más útiles ya lo hemos empleado varias veces. Cuando incluimos el
código de modo que no se ejecute hasta que el documento no esté disponible, lo
hacemos a través del evento ready() asociado al objeto documento: $
(document).ready(). Otros eventos que usaremos frecuentemente son:

El evento click() captura la acción de hacer clic con el botón principal del ratón.


$(function(){
$("html").click(function(){
alert("Se ha hecho clic con el botón izquierdo");
});
});

<section>
<img src="https://i.postimg.cc/7LpJcm4t/logo.jpg" alt="Logo CRFPTIC">
<h1>Curso HTML, CSS y Javascript <span>avanzado</span></h1>
<h2>CRFPTIC</h2>
</section>

section{
background-color:whitesmoke;
padding:2ex;
width: 500px;
display:grid;
grid-template-columns:1fr 3fr;
grid-template-rows:1fr 1fr auto;
border-radius:7px;
}
img{
grid-area: 1/1/3/2;
margin:auto;
display:block;
width:90%;
filter: opacity(.85);
}
h1{
grid-area:1/2/2/3;
margin:auto 0 auto 1em;
}
h2{
grid-area:2/2/3/3;
margin:auto 0 auto 1em;
}
body{
background-color:black;
color:gray;
}

$(function(){
$("html").click(function(){
alert("Se ha hecho clic con el botón izquierdo");
});
});

Otros eventos propios de los dispositivos de entrada son:


.dblclick() Se produce al hacer doble clic con el ratón.
Se activa al ubicar el puntero del ratón sobre un elemento.
.hover() Desencadena dos acciones: una al entrar y otra al salir el
puntero del ratón del área del elemento. Es la combinación
de los dos siguientes eventos.
.mouseenter() La función asociada se ejecutará al entrar el puntero del ratón
en el área del elemento.
.mouseleave() La función se ejecutará cuando el puntero del ratón sale del
área del elemento.
.mousedown() Se produce este evento al presionar cualquiera de los tres
botones del ratón.
.mouseup() Se emplea para ejecutar una función al liberar la
pulsación sobre cualquiera de los tres botones del ratón.
.contextmenu() Hacer clic con el botón derecho del ratón provoca este evento.
.keypress() Se activa al pulsar una tecla.

Entre los eventos que pueden ser de utilidad para manejar formularios están:

.submit() Se activa al enviar el formulario.

.focus() El evento se desencadena al coger el foco un elemento.

.blur() Se produce cuando un elemento pierde el foco.

.change() Es el evento que se detecta a modificar el valor de un elemento.

Otros eventos:

Una lista completa de los eventos disponibles en jQuery la podemos consultar en su


página de referencia.
El elemento que se usa con mayor frecuencia cuando trabajamos con eventos es on.
Ofrece, de forma similar al método nativo de javascript addEventListener, un
método para asociar funciones a eventos. Veamos un ejemplo de su uso:
$(".boton").on("click", function(){
$("img").hide();
});

La diferencia que aporta el uso de on frente a la asociación directa del evento del tipo:
$(".boton").click(function(){
$("img").hide();
});

es que, mediante el uso de on podemos asociar diferentes eventos al mismo elemento,


además de proporcionarnos un método simple para eliminar los eventos cuando lo
precisemos. Además, la asociación directa de eventos solo la podemos emplear con
elementos que existan en el momento de la asociación; mientras que con on podemos
asociar eventos a elementos que potencialmente pueden existir más adelante.

Para asociar diferentes eventos al elemento los enlazaremos mediante comas:

<section>
<img src="https://i.postimg.cc/7LpJcm4t/logo.jpg" alt="Logo CRFPTIC">
<h1>Curso HTML, CSS y Javascript <span>avanzado</span></h1>
<h2>CRFPTIC</h2>
</section>

section{
background-color:whitesmoke;
padding:2ex;
width: 500px;
display:grid;
grid-template-columns:1fr 3fr;
grid-template-rows:1fr 1fr auto;
border-radius:7px;
}
img{
grid-area: 1/1/3/2;
margin:auto;
display:block;
width:90%;
filter: opacity(.85);
}
h1{
grid-area:1/2/2/3;
margin:auto 0 auto 1em;
}
h2{
grid-area:2/2/3/3;
margin:auto 0 auto 1em;
}
body{
background-color:black;
color:gray;
}

$(function(){
$("html").on({
click: function(){
alert("Se ha hecho clic con el botón izquierdo");
},
contextmenu: function(){
alert("Se ha hecho clic con el botón derecho");
}
});
});

Hay eventos que ya tienen asociada alguna acción por defecto por parte del navegador.
En el ejemplo anterior, al hacer clic con el botón derecho, además de aparecer el
mensaje programado aparecerá el menú contextual. Para evitar este comportamiento
podemos emplear el método preventDefault() asociándolo al evento que
desencadenó la función:
<section>
<img src="https://i.postimg.cc/7LpJcm4t/logo.jpg" alt="Logo CRFPTIC">
<h1>Curso HTML, CSS y Javascript <span>avanzado</span></h1>
<h2>CRFPTIC</h2>
</section>

section{
background-color:whitesmoke;
padding:2ex;
width: 500px;
display:grid;
grid-template-columns:1fr 3fr;
grid-template-rows:1fr 1fr auto;
border-radius:7px;
}
img{
grid-area: 1/1/3/2;
margin:auto;
display:block;
width:90%;
filter: opacity(.85);
}
h1{
grid-area:1/2/2/3;
margin:auto 0 auto 1em;
}
h2{
grid-area:2/2/3/3;
margin:auto 0 auto 1em;
}
body{
background-color:black;
color:gray;
}

$(function(){
$("html").on({
click: function(){
alert("Se ha hecho clic con el botón izquierdo");
},
contextmenu: function(e){
e.preventDefault();
alert("Se ha hecho clic con el botón derecho");
}
});
});

Reto
Ocultar

Sobre el ejercicio propuesto hay que añadir funcionalidad al botón, de modo que al
hacer clic en él oculte —hide()— las imágenes; y que las muestre —show()— al
hacer clic con el botón derecho.

<div>
<button class="boton">Clic para eliminar o clic derecho para mostrar
imágenes</button>
<figure>
<img alt="Gilbert Stuart Williamstown Portrait of George Washington.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Gilbert_Stuart
_Williamstown_Portrait_of_George_Washington.jpg/160px-
Gilbert_Stuart_Williamstown_Portrait_of_George_Washington.jpg" width="160"
height="194">
<figcaption>George Washington</figcaption>
</figure>
<p>The <a href="/wiki/President_of_the_United_States" title="President of the
United States">president of the United States</a> is the <a
href="/wiki/Head_of_state" title="Head of state">head of state</a> and <a
href="/wiki/Head_of_government" title="Head of government">head of
government</a> of the <a href="/wiki/United_States" title="United
States">United States</a>, <a href="/wiki/Indirectly_elected" class="mw-
redirect" title="Indirectly elected">indirectly elected</a> to a four-year <a
href="/wiki/Term_of_office" title="Term of office">term</a> by the American
people through the <a href="/wiki/United_States_Electoral_College"
title="United States Electoral College">Electoral College</a>. The
officeholder leads the <a href="/wiki/Executive_(government)"
title="Executive (government)">executive branch</a> of the <a
href="/wiki/Federal_government_of_the_United_States" title="Federal
government of the United States">federal government</a> and is the <a
href="/wiki/Commander-in-chief" title="Commander-in-chief">commander-in-
chief</a> of the <a href="/wiki/United_States_Armed_Forces" title="United
States Armed Forces">United States Armed Forces</a>.
</p>

<figure>
<img alt="Grover Cleveland - NARA - 518139 (cropped).jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Grover_Clevela
nd_-_NARA_-_518139_%28cropped%29.jpg/160px-Grover_Cleveland_-_NARA_-_518139_
%28cropped%29.jpg" width="160" height="206">
<figcaption>Grover Cleveland</figcaption>
</figure>
<p>Since the office was established in 1789, there have been 45 presidencies,
while 44 men have served as president. The first, <a
href="/wiki/George_Washington" title="George Washington">George
Washington</a>, won a unanimous vote of the Electoral College. <a
href="/wiki/Grover_Cleveland" title="Grover Cleveland">Grover Cleveland</a>
served two non-consecutive terms (the only president to have done so) and is
therefore counted as the 22nd and 24th president of the United States.
</p>

<figure><img alt="George H. W. Bush presidential portrait (cropped).jpg"


src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ee/George_H._W._B
ush_presidential_portrait_%28cropped%29.jpg/160px-
George_H._W._Bush_presidential_portrait_%28cropped%29.jpg" width="160"
height="210">
<figcaption>George H. W. Bush</figcaption>
</figure>
<p>There are four <a href="/wiki/Living_presidents_of_the_United_States"
title="Living presidents of the United States">living former presidents</a>.
The most recent to die was <a href="/wiki/George_H._W._Bush" title="George H.
W. Bush">George H. W. Bush</a>, <a
href="/wiki/Death_and_state_funeral_of_George_H._W._Bush" title="Death and
state funeral of George H. W. Bush">on November 30, 2018</a>.
</p>

<figure>
<img alt="William Henry Harrison daguerreotype edit.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/William_Henry_
Harrison_daguerreotype_edit.jpg/160px-
William_Henry_Harrison_daguerreotype_edit.jpg" width="160" height="190">
<figcaption>William Henry Harrison</figcaption>
</figure>
<p>The presidency of <a href="/wiki/William_Henry_Harrison" title="William
Henry Harrison">William Henry Harrison</a>, who died 31 days after taking
office in 1841, was the shortest in American history. <a
href="/wiki/Franklin_D._Roosevelt" title="Franklin D. Roosevelt">Franklin D.
Roosevelt</a> served the longest, over twelve years, before dying early in
his fourth term in 1945. He is the only U.S. president to have served more
than two terms. Since the ratification of the <a href="/wiki/Twenty-
second_Amendment_to_the_United_States_Constitution" title="Twenty-second
Amendment to the United States Constitution">Twenty-second Amendment to the
United States Constitution</a> in 1951, no person may be elected president
more than twice, and no one who has served more than two years of a term to
which someone else was elected may be elected more than once.<sup
id="cite_ref-1" class="reference"><a href="#cite_note-1">[1]</a></sup>
</p>

<figure>
<img alt="Zachary Taylor restored and cropped.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Zachary_Taylor
_restored_and_cropped.jpg/160px-Zachary_Taylor_restored_and_cropped.jpg"
width="160" height="210">
<figcaption>Zachary Taylor</figcaption>
</figure>
<p>Of those who have served as the nation's president, four died in office of
natural causes (William Henry Harrison, <a href="/wiki/Zachary_Taylor"
title="Zachary Taylor">Zachary Taylor</a>, <a href="/wiki/Warren_G._Harding"
title="Warren G. Harding">Warren G. Harding</a>, and Franklin D. Roosevelt),
four were <a
href="/wiki/List_of_United_States_presidential_assassination_attempts_and_plo
ts" title="List of United States presidential assassination attempts and
plots">assassinated</a> (<a href="/wiki/Abraham_Lincoln" title="Abraham
Lincoln">Abraham Lincoln</a>, <a href="/wiki/James_A._Garfield" title="James
A. Garfield">James A. Garfield</a>, <a href="/wiki/William_McKinley"
title="William McKinley">William McKinley</a> and <a
href="/wiki/John_F._Kennedy" title="John F. Kennedy">John F. Kennedy</a>),
and one resigned (<a href="/wiki/Richard_Nixon" title="Richard Nixon">Richard
Nixon</a>, facing <a href="/wiki/Impeachment_process_against_Richard_Nixon"
title="Impeachment process against Richard Nixon">impeachment</a>). <a
href="/wiki/John_Tyler" title="John Tyler">John Tyler</a> was the first vice
president to assume the presidency during a presidential term, and set the
precedent that a vice president who does so becomes the fully functioning
president with his presidency, as opposed to a <a
href="/wiki/Caretaker_president" class="mw-redirect" title="Caretaker
president">caretaker president</a>. The <a href="/wiki/Twenty-
fifth_Amendment_to_the_United_States_Constitution" title="Twenty-fifth
Amendment to the United States Constitution">Twenty-fifth Amendment</a> to
the Constitution put Tyler's precedent into law in 1967. It also established
a mechanism by which an intra-term vacancy in the vice presidency could be
filled. Richard Nixon was the first president to fill a vacancy under this
provision when he <a
href="/wiki/1973_United_States_vice_presidential_confirmation" title="1973
United States vice presidential confirmation">selected</a> <a
href="/wiki/Gerald_Ford" title="Gerald Ford">Gerald Ford</a> for the office
following <a href="/wiki/Spiro_Agnew" title="Spiro Agnew">Spiro Agnew</a>'s
resignation in 1973. The following year, Ford became the second to do so when
he <a href="/wiki/1974_United_States_vice_presidential_confirmation"
title="1974 United States vice presidential confirmation">chose</a> <a
href="/wiki/Nelson_Rockefeller" title="Nelson Rockefeller">Nelson
Rockefeller</a> to succeed him after he acceded to the presidency. As no
mechanism existed for filling an intra-term vacancy in the vice presidency
before 1967, the office was left vacant until filled through the next ensuing
presidential election and subsequent inauguration.
</p>

<figure>
<img alt="Thomas Jefferson by Rembrandt Peale, 1800.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Thomas_Jeffers
on_by_Rembrandt_Peale%2C_1800.jpg/160px-Thomas_Jefferson_by_Rembrandt_Peale
%2C_1800.jpg" width="160" height="191">
<figcaption>Thomas Jefferson</figcaption>
</figure>
<p>Throughout most of its history, <a href="/wiki/American_politics"
class="mw-redirect" title="American politics">American politics</a> has been
dominated by <a href="/wiki/Political_parties_in_the_United_States"
title="Political parties in the United States">political parties</a>. The
Constitution is silent on the issue of political parties, and at the time it
came into force in 1789, no organized parties existed. Soon after the <a
href="/wiki/1st_United_States_Congress" title="1st United States
Congress">1st Congress</a> convened, factions began rallying around dominant
<a href="/wiki/Presidency_of_George_Washington" title="Presidency of George
Washington">Washington administration</a> officials, such as <a
href="/wiki/Alexander_Hamilton" title="Alexander Hamilton">Alexander
Hamilton</a> and <a href="/wiki/Thomas_Jefferson" title="Thomas
Jefferson">Thomas Jefferson</a>. Greatly concerned about the capacity of
political parties to destroy the fragile unity holding the nation together,
Washington remained unaffiliated with any political faction or party
throughout his eight-year presidency. He was, and remains, the only U.S.
president never affiliated with a political party.<sup id="cite_ref-2"
class="reference"><a href="#cite_note-2">[2]</a></sup>
</p>
</div>

button{
width:100%;
padding:1em 0;
cursor:pointer;
}
figure{
width:160px;
}
figcaption{
text-align:center;
}
figure:nth-of-type(2n){
clear:right;
float:right;
}
figure:nth-of-type(2n+1){
clear:left;
float:left;
}
Usaremos on para asociar las acciones hide() y show() a los eventos
correspondientes, evitando, en el caso del clic derecho, la apertura del
menú contextual.
$(function(){
$(".boton").on({
click: function(){
$("figure").hide();
},
contextmenu: function(e){
e.preventDefault();
$("figure").show();
}
});
});

<div>
<button class="boton">Clic para eliminar o clic derecho para mostrar
imágenes</button>
<figure>
<img alt="Gilbert Stuart Williamstown Portrait of George Washington.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Gilbert_Stuart
_Williamstown_Portrait_of_George_Washington.jpg/160px-
Gilbert_Stuart_Williamstown_Portrait_of_George_Washington.jpg" width="160"
height="194">
<figcaption>George Washington</figcaption>
</figure>
<p>The <a href="/wiki/President_of_the_United_States" title="President of the
United States">president of the United States</a> is the <a
href="/wiki/Head_of_state" title="Head of state">head of state</a> and <a
href="/wiki/Head_of_government" title="Head of government">head of
government</a> of the <a href="/wiki/United_States" title="United
States">United States</a>, <a href="/wiki/Indirectly_elected" class="mw-
redirect" title="Indirectly elected">indirectly elected</a> to a four-year <a
href="/wiki/Term_of_office" title="Term of office">term</a> by the American
people through the <a href="/wiki/United_States_Electoral_College"
title="United States Electoral College">Electoral College</a>. The
officeholder leads the <a href="/wiki/Executive_(government)"
title="Executive (government)">executive branch</a> of the <a
href="/wiki/Federal_government_of_the_United_States" title="Federal
government of the United States">federal government</a> and is the <a
href="/wiki/Commander-in-chief" title="Commander-in-chief">commander-in-
chief</a> of the <a href="/wiki/United_States_Armed_Forces" title="United
States Armed Forces">United States Armed Forces</a>.
</p>

<figure>
<img alt="Grover Cleveland - NARA - 518139 (cropped).jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Grover_Clevela
nd_-_NARA_-_518139_%28cropped%29.jpg/160px-Grover_Cleveland_-_NARA_-_518139_
%28cropped%29.jpg" width="160" height="206">
<figcaption>Grover Cleveland</figcaption>
</figure>
<p>Since the office was established in 1789, there have been 45 presidencies,
while 44 men have served as president. The first, <a
href="/wiki/George_Washington" title="George Washington">George
Washington</a>, won a unanimous vote of the Electoral College. <a
href="/wiki/Grover_Cleveland" title="Grover Cleveland">Grover Cleveland</a>
served two non-consecutive terms (the only president to have done so) and is
therefore counted as the 22nd and 24th president of the United States.
</p>

<figure><img alt="George H. W. Bush presidential portrait (cropped).jpg"


src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ee/George_H._W._B
ush_presidential_portrait_%28cropped%29.jpg/160px-
George_H._W._Bush_presidential_portrait_%28cropped%29.jpg" width="160"
height="210">
<figcaption>George H. W. Bush</figcaption>
</figure>
<p>There are four <a href="/wiki/Living_presidents_of_the_United_States"
title="Living presidents of the United States">living former presidents</a>.
The most recent to die was <a href="/wiki/George_H._W._Bush" title="George H.
W. Bush">George H. W. Bush</a>, <a
href="/wiki/Death_and_state_funeral_of_George_H._W._Bush" title="Death and
state funeral of George H. W. Bush">on November 30, 2018</a>.
</p>

<figure>
<img alt="William Henry Harrison daguerreotype edit.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/William_Henry_
Harrison_daguerreotype_edit.jpg/160px-
William_Henry_Harrison_daguerreotype_edit.jpg" width="160" height="190">
<figcaption>William Henry Harrison</figcaption>
</figure>
<p>The presidency of <a href="/wiki/William_Henry_Harrison" title="William
Henry Harrison">William Henry Harrison</a>, who died 31 days after taking
office in 1841, was the shortest in American history. <a
href="/wiki/Franklin_D._Roosevelt" title="Franklin D. Roosevelt">Franklin D.
Roosevelt</a> served the longest, over twelve years, before dying early in
his fourth term in 1945. He is the only U.S. president to have served more
than two terms. Since the ratification of the <a href="/wiki/Twenty-
second_Amendment_to_the_United_States_Constitution" title="Twenty-second
Amendment to the United States Constitution">Twenty-second Amendment to the
United States Constitution</a> in 1951, no person may be elected president
more than twice, and no one who has served more than two years of a term to
which someone else was elected may be elected more than once.<sup
id="cite_ref-1" class="reference"><a href="#cite_note-1">[1]</a></sup>
</p>

<figure>
<img alt="Zachary Taylor restored and cropped.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Zachary_Taylor
_restored_and_cropped.jpg/160px-Zachary_Taylor_restored_and_cropped.jpg"
width="160" height="210">
<figcaption>Zachary Taylor</figcaption>
</figure>
<p>Of those who have served as the nation's president, four died in office of
natural causes (William Henry Harrison, <a href="/wiki/Zachary_Taylor"
title="Zachary Taylor">Zachary Taylor</a>, <a href="/wiki/Warren_G._Harding"
title="Warren G. Harding">Warren G. Harding</a>, and Franklin D. Roosevelt),
four were <a
href="/wiki/List_of_United_States_presidential_assassination_attempts_and_plo
ts" title="List of United States presidential assassination attempts and
plots">assassinated</a> (<a href="/wiki/Abraham_Lincoln" title="Abraham
Lincoln">Abraham Lincoln</a>, <a href="/wiki/James_A._Garfield" title="James
A. Garfield">James A. Garfield</a>, <a href="/wiki/William_McKinley"
title="William McKinley">William McKinley</a> and <a
href="/wiki/John_F._Kennedy" title="John F. Kennedy">John F. Kennedy</a>),
and one resigned (<a href="/wiki/Richard_Nixon" title="Richard Nixon">Richard
Nixon</a>, facing <a href="/wiki/Impeachment_process_against_Richard_Nixon"
title="Impeachment process against Richard Nixon">impeachment</a>). <a
href="/wiki/John_Tyler" title="John Tyler">John Tyler</a> was the first vice
president to assume the presidency during a presidential term, and set the
precedent that a vice president who does so becomes the fully functioning
president with his presidency, as opposed to a <a
href="/wiki/Caretaker_president" class="mw-redirect" title="Caretaker
president">caretaker president</a>. The <a href="/wiki/Twenty-
fifth_Amendment_to_the_United_States_Constitution" title="Twenty-fifth
Amendment to the United States Constitution">Twenty-fifth Amendment</a> to
the Constitution put Tyler's precedent into law in 1967. It also established
a mechanism by which an intra-term vacancy in the vice presidency could be
filled. Richard Nixon was the first president to fill a vacancy under this
provision when he <a
href="/wiki/1973_United_States_vice_presidential_confirmation" title="1973
United States vice presidential confirmation">selected</a> <a
href="/wiki/Gerald_Ford" title="Gerald Ford">Gerald Ford</a> for the office
following <a href="/wiki/Spiro_Agnew" title="Spiro Agnew">Spiro Agnew</a>'s
resignation in 1973. The following year, Ford became the second to do so when
he <a href="/wiki/1974_United_States_vice_presidential_confirmation"
title="1974 United States vice presidential confirmation">chose</a> <a
href="/wiki/Nelson_Rockefeller" title="Nelson Rockefeller">Nelson
Rockefeller</a> to succeed him after he acceded to the presidency. As no
mechanism existed for filling an intra-term vacancy in the vice presidency
before 1967, the office was left vacant until filled through the next ensuing
presidential election and subsequent inauguration.
</p>

<figure>
<img alt="Thomas Jefferson by Rembrandt Peale, 1800.jpg"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Thomas_Jeffers
on_by_Rembrandt_Peale%2C_1800.jpg/160px-Thomas_Jefferson_by_Rembrandt_Peale
%2C_1800.jpg" width="160" height="191">
<figcaption>Thomas Jefferson</figcaption>
</figure>
<p>Throughout most of its history, <a href="/wiki/American_politics"
class="mw-redirect" title="American politics">American politics</a> has been
dominated by <a href="/wiki/Political_parties_in_the_United_States"
title="Political parties in the United States">political parties</a>. The
Constitution is silent on the issue of political parties, and at the time it
came into force in 1789, no organized parties existed. Soon after the <a
href="/wiki/1st_United_States_Congress" title="1st United States
Congress">1st Congress</a> convened, factions began rallying around dominant
<a href="/wiki/Presidency_of_George_Washington" title="Presidency of George
Washington">Washington administration</a> officials, such as <a
href="/wiki/Alexander_Hamilton" title="Alexander Hamilton">Alexander
Hamilton</a> and <a href="/wiki/Thomas_Jefferson" title="Thomas
Jefferson">Thomas Jefferson</a>. Greatly concerned about the capacity of
political parties to destroy the fragile unity holding the nation together,
Washington remained unaffiliated with any political faction or party
throughout his eight-year presidency. He was, and remains, the only U.S.
president never affiliated with a political party.<sup id="cite_ref-2"
class="reference"><a href="#cite_note-2">[2]</a></sup>
</p>
</div>

button{
width:100%;
padding:1em 0;
cursor:pointer;
}
figure{
width:160px;
}
figcaption{
text-align:center;
}
figure:nth-of-type(2n){
clear:right;
float:right;
}
figure:nth-of-type(2n+1){
clear:left;
float:left;
}

$(function(){
$(".boton").on({
click: function(){
$("figure").hide();
},
contextmenu: function(e){
e.preventDefault();
$("figure").show();
}
});
});

Acciones
Ocultar

Para completar los elementos básicos que intervienen en la mayoría de las instrucciones,
veremos las acciones que proporciona el lenguaje. Una vez seleccionado el elemento y
determinado el evento desencadenador, queda por conocer la acción que el elemento
realizará cuando se active el evento. 

Ya hemos visto alguna: hide() y show() ocultan y muestran el elemento,


respectivamente.
$(function(){
$(".boton").on({
click: function(){
$("figure").hide();
},
contextmenu: function(){
$("figure").show();
}
});
});

Si queremos ocultar o mostrar elementos, pero mediante un efecto de desvanecimiento,


disponemos de las acciones fadeOut() y fadeIn().
<section>
<img src="https://i.postimg.cc/7LpJcm4t/logo.jpg" alt="Logo CRFPTIC">
<h1>Curso HTML, CSS y Javascript <span>avanzado</span></h1>
<h2>CRFPTIC</h2>
</section>

section{
background-color:whitesmoke;
padding:2ex;
width: 500px;
display:grid;
grid-template-columns:1fr 3fr;
grid-template-rows:1fr 1fr auto;
border-radius:7px;
}
img{
grid-area: 1/1/3/2;
margin:auto;
display:block;
width:90%;
filter: opacity(.85);
}
h1{
grid-area:1/2/2/3;
margin:auto 0 auto 1em;
}
h2{
grid-area:2/2/3/3;
margin:auto 0 auto 1em;
}
body{
background-color:black;
color:gray;
}

$(function(){
$("html").on({
click: function(){
$("img").fadeOut();
},
contextmenu: function(e){
e.preventDefault();
$("img").fadeIn();
}
});
});

 Si empleamos slideUp() o slideDown() el elemento se mostrará u ocultará


empleando un desplazamiento vertical:

<section>
<img src="https://i.postimg.cc/7LpJcm4t/logo.jpg" alt="Logo CRFPTIC">
<h1>Curso HTML, CSS y Javascript <span>avanzado</span></h1>
<h2>CRFPTIC</h2>
</section>

section{
background-color:whitesmoke;
padding:2ex;
width: 500px;
display:grid;
grid-template-columns:1fr 3fr;
grid-template-rows:1fr 1fr auto;
border-radius:7px;
}
img{
grid-area: 1/1/3/2;
margin:auto;
display:block;
width:90%;
filter: opacity(.85);
}
h1{
grid-area:1/2/2/3;
margin:auto 0 auto 1em;
}
h2{
grid-area:2/2/3/3;
margin:auto 0 auto 1em;
}
body{
background-color:black;
color:gray;
}

$(function(){
$("html").on({
click: function(){
$("img").slideUp();
},
contextmenu: function(e){
e.preventDefault();
$("img").slideDown();
}
});
});

En los ejemplos anteriores se usan como eventos el clic derecho y el clic con el botón
izquierdo del ratón. Las siguientes acciones permiten usar el mismo evento para mostrar
u ocultar elementos. toggle(), por ejemplo, aplica hide() si el elemento está
visible y show() si está oculto:

<section>
<img src="https://i.postimg.cc/7LpJcm4t/logo.jpg" alt="Logo CRFPTIC">
<h1>Curso HTML, CSS y Javascript <span>avanzado</span></h1>
<h2>CRFPTIC</h2>
</section>

section{
background-color:whitesmoke;
padding:2ex;
width: 500px;
display:grid;
grid-template-columns:1fr 3fr;
grid-template-rows:1fr 1fr auto;
border-radius:7px;
}
img{
grid-area: 1/1/3/2;
margin:auto;
display:block;
width:90%;
filter: opacity(.85);
}
h1{
grid-area:1/2/2/3;
margin:auto 0 auto 1em;
}
h2{
grid-area:2/2/3/3;
margin:auto 0 auto 1em;
}
body{
background-color:black;
color:gray;
}

$(function(){
$("html").on({
click: function(){
$("img").toggle();
}
});
});

Las acciones fadeToggle() y slideToggle() hacen lo mismo, pero aplicando los efectos
de fundido y desplazamiento, respectivamente.
<section>
<img src="https://i.postimg.cc/7LpJcm4t/logo.jpg" alt="Logo CRFPTIC">
<h1>Curso HTML, CSS y Javascript <span>avanzado</span></h1>
<h2>CRFPTIC</h2>
</section>

section{
background-color:whitesmoke;
padding:2ex;
width: 500px;
display:grid;
grid-template-columns:1fr 3fr;
grid-template-rows:1fr 1fr auto;
border-radius:7px;
}
img{
grid-area: 1/1/3/2;
margin:auto;
display:block;
width:90%;
filter: opacity(.85);
}
h1{
grid-area:1/2/2/3;
margin:auto 0 auto 1em;
}
h2{
grid-area:2/2/3/3;
margin:auto 0 auto 1em;
}
body{
background-color:black;
color:gray;
}

$(function(){
$("html").on({
click: function(){
$("img").fadeToggle();
}
});
});
<section>
<img src="https://i.postimg.cc/7LpJcm4t/logo.jpg" alt="Logo CRFPTIC">
<h1>Curso HTML, CSS y Javascript <span>avanzado</span></h1>
<h2>CRFPTIC</h2>
</section>

section{
background-color:whitesmoke;
padding:2ex;
width: 500px;
display:grid;
grid-template-columns:1fr 3fr;
grid-template-rows:1fr 1fr auto;
border-radius:7px;
}
img{
grid-area: 1/1/3/2;
margin:auto;
display:block;
width:90%;
filter: opacity(.85);
}
h1{
grid-area:1/2/2/3;
margin:auto 0 auto 1em;
}
h2{
grid-area:2/2/3/3;
margin:auto 0 auto 1em;
}
body{
background-color:black;
color:gray;
}
$(function(){
$("html").on({
click: function(){
$("img").slideToggle();
}
});
});

Reto
Ocultar

Las ventanas modales son cuadros que aparecen sobre la página, bloqueando las
acciones para concentrar la atención del usuario en el mensaje. Se activan al hacer clic
en un enlace o botón y deben servir para prevenir al usuario de errores o para facilitar la
realización de una acción sin necesidad de salir de la página.

En un documento crea un enlace que, al pulsarlo, muestre una ventana modal para
suscribirse a una lista de correo. No es necesario que el formulario funcione, el objetivo
del reto es lograr activar y cerrar una ventana modal mediante alguna de las acciones de
jQuery.

El HTML del documento será muy simple: un article con


clase contenido, que almacena el contenido visible de la página; y otro
con clase modal que será la ventana para solicitar el correo electrónico. Se
ha dado la clase cerrar a los elementos que desencadenarán la acción de
mostrar/ocultar la ventana modal.
<article class="modal">
<form action="#">
<p><label for="mail">Correo-e:&nbsp; </label><input id="mail"
type="email"></p>
<p><button class="cerrar" type="submit">Enviar</button><button
class="cerrar" type="button">Cerrar</button></p>
</form>
</article>
<article class="contenido">
<p><a class="cerrar" href="#">Pulsa aquí</a> para suscribirte a nuestra
lista de correo.</p>
</article>

Los estilos mínimos ocultan, dan forma y ubican el article de


clase modal sobre la página, con un fondo semitransparente; y el formulario
centrado en la ventana.
.modal{
display:none;
position:absolute;
width:100vw;
height:100vh;
background-color:rgba(255,255,255,.7)
}
form{
position:absolute;
width:50%;
top:calc(50vh - 120px);
left:calc(50vw - 25%);
background-color:grey;
box-sizing:border-box;
padding:2em 3em;
min-width:338px;
}

Sobre esta página, haremos que la ventana se muestre cuando se haga clic
en el enlace; y se oculte al pulsar alguno de los botones del formulario.
$(function(){
$(".cerrar").on({
click: function(e){
e.preventDefault();
$(".modal").fadeToggle();
}
});
});
<article class="modal">
<form action="#">
<p><label for="mail">Correo-e:&nbsp; </label><input id="mail"
type="email"></p>
<p><button class="cerrar" type="submit">Enviar</button><button
class="cerrar" type="button">Cerrar</button></p>
</form>
</article>

<article class="contenido">
<p><a class="cerrar" href="#">Pulsa aquí</a> para suscribirte a nuestra
lista de correo.</p>
</article>

body,p{margin:0;}
.modal{
display:none;
position:absolute;
width:100vw;
height:100vh;
background-color:rgba(255,255,255,.7)
}
form{
position:absolute;
width:50%;
top:calc(50vh - 120px);
left:calc(50vw - 25%);
background-color:grey;
box-sizing:border-box;
padding:2em 3em;
min-width:338px;
}
form>p{
display:flex;
align-items:center;
margin:10px 0;
}
input,button{
flex:1 auto;
padding:1ex 0;
}
.contenido p{
margin:1em;
font-family:arial,sans-serif;
font-size:110%;
font-weight:bolder;
}

$(function(){
$(".cerrar").on({
click: function(e){
e.preventDefault();
$(".modal").fadeToggle();
}
});
});

También podría gustarte