Iniciando en Jquery, buenas practicas, ejercicios para practicar, selectores y mas

Iniciando en Jquery, buenas practicas, ejercicios para practicar, selectores y mas

Que podemos encontrar en estos apuntes.

  1. Usando elementos y cómo accederlos en el DOM.
  2. Como usar listas elementos los primeros los ultimos, o elementos que derivan directamente de otros.
  3. como seleccionar múltiples elementos en una misma linea (separar por commas).
  4. Como agregar css o clases a elementos y agregar diferentes estilos, agregar o quitar clases o usar el toggleClass
  5. Como agregar elementos al Dom antes o despues de algun elemento, como ocultarlos, mostrarlos, cambiarlos de lugar.
  6. Como agregar texto o html a un elemento deseado, o como agregarlo al inicio o al final de su contenido actual o sea solo modificarlo.
  7. Como crear funciones, y las funciones anonimas en jquery
  8. Uso de algunos eventos como click, hover, keypress, preventDefault, entre otros.
  9. Algunos efectos de animacion para mostrar u ocultar.
  10. Hacer algunos calculos apartir de la obtencion de un valor.
  11. Como usar el hover class para agregar una clase al momento del hover y quitarlo al alejarse, usado de la forma larga y compacta.

El arte de la seleccion

The courses recomend use class + clase o id example:
Es mas recomendable al momento de usar seleccion de tags usar por ejemplo el tipo de selector mas las clase o id del elemento.

$("p.myid");
$("h3#myclase");

o multiple

 $("h3.errors, p.errors");

if we want to search the first paragraph in the DOM we can write:

 $("p:first");

direct descendants (descendientes directos de un elemnto)

$("body > li#hola");

Lo anterior buscara descendientes directos de body en caso de que este dentro de otro contenedor no lo encontrara por que como quien dice debe de estar en raiz para que lo encuentre pero se aplica a cualquier descendiente dentro de cualquier contenedor

Using white spaces

$("p #final")

Lo anterior buscara todo los elementos con id final pero que no sean parrafos

Si queremos que solo nos muestre los elementos que descienden de cierto elemento

$("#content > p");

Si quisieramos por ejemplo

Select all the rows and seats in first class, everything with an <LI>.

<div id="seating_chart">
<ul id="first_class">
   <li id="row_1">
    <ul>
     <li></li>
     <li></li>
     <li></li>
    </ul>
   </li>
  <li id="row_2">
   <ul>
    <li></li>
    <li></li>
    <li></li>
   </ul>
  </li>
</ul>
</div>

Console

$('ul#first_class li');

using the before exercise do the next:
Select all of the <LI> tags that are either seats or aisles (but not the rows) in first_class using a single selector. Your selector will need four levels of DOM hierarchy.

the answer is:

$("ul#first_class li li")

if we want select all the li (seats) with no other rows or elements


<div id="seating_chart">
 <ul id="first_class">
   <li id="row_1">
    <ul>
     <li></li>
     <li></li>
     <li></li>
    </ul>
   </li>
   <li id="row_2">
    <ul>
     <li></li>
     <li></li>
     <li></li>
    </ul>
   </li>
 </ul>
</div>

The solution is:

$('li li');

Select the first row on the plane without using any DOM ID’s. Instead, rely on the ‘:first’ pseudo-class.


<div id="seating_chart">
 <ul id="first_class">
   <li id="row_1">
    <ul>
     <li></li>
     <li></li>
     <li></li>
    </ul>
   </li>
   <li id="row_2">
    <ul>
     <li></li>
     <li></li>
     <li></li>
    </ul>
   </li>
 </ul>
</div>

The solution is:

$('li:first');

and to select the last li use the

$("li:last")

Direct descendants
Select all the rows in the economy class by selecting the direct descendants from ul#economy_class.


<div id="seating_chart">
 <ul id="first_class">
   <li id="row_1">
    <ul>
     <li></li>
     <li></li>
     <li></li>
    </ul>
   </li>
   <li id="row_2">
    <ul>
     <li></li>
     <li></li>
     <li></li>
    </ul>
   </li>
 </ul>
</div>


<strong>The solution is:</strong>


Bringing it all together
Find the first row of first and economy class without relying on the row's ID. Instead use the direct descendant marker and the :first pseudo-class. GOTCHA: You'll need two selectors.



<div id="seating_chart">
 <ul id="first_class">
   <li id="row_1">
    <ul>
     <li></li>
     <li></li>
     <li></li>
    </ul>
   </li>
   <li id="row_2">
    <ul>
     <li></li>
     <li></li>
     <li></li>
    </ul>
   </li>
 </ul>
</div>

the solution is:

$('ul#economy_class > li:first, li:first');

Find all the window seats (a & d in first class, and a & f in economy) using any tools necessary

how to select classes or id with spaces in jquery

<div id="seating_chart">
<ul id="first_class">
<li id="row_1">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</li>
<li id="row_2">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</li>
</ul>
</div>

the solution is:

$('li.premium.a, li.premium.d, li.a, li.f');

Find all of the aisle seats (meaning, those LI elements immediately before and after the LI.aisle) using any tools necessary.

<div id="seating_chart">
 <ul id="first_class">
  <li id="row_1">
    <ul>
     <li></li>
     <li></li>
     <li></li>
     <li></li>
     <li></li>
    </ul>
  </li>
  <li id="row_2">
   <ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
   </ul>
  </li>
 </ul>
 <ul id="economy_class">
   <li id="row_3">
    <ul>
     <li></li>
     <li></li>
     <li></li>
     <li></li>
     <li></li>
     <li></li>
     <li></li>
    </ul>
   </li>
   <li id="row_4">
    <ul>
     <li></li>
     <li></li>
     <li></li>
     <li></li>
     <li></li>
     <li></li>
     <li></li>
    </ul>
   </li>
  <li id="row_5">
   <ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
   </ul>
  </li>
  <li id="row_6">
   <ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
   </ul>
  </li>
 </ul>
</div>

the solution is:

$('li.premium.b, li.premium.c, ul#economy_class > li.c, ul#economy_class > li.cli.d');
 $('li.premium.b, li.premium.c, li#row_3 > ul li.c,li#row_3 >ul li.d, li#row_4 > ul li.c,li#row_4>ul li.d, li#row_5 > ul li.c,li#row_5 >ul li.d, li#row_6 > ul li.c,li#row_6 >ul li.d');

TERCER NIVEL DE JQUERY AIR

Manipulation de estilos

For update the font-size in a div with class name

$("div.name").css("font-size","24px").
 css("background-color","black").
 css("width","24px");

Add class to some id or class

$("p.contenido").addClass("nueva_clase");

Remove a class

$("p.contenido").removeClass("nueva_clase");

Using toggleclass

$("p.contenido").toggleClass("nueva_clase");

Usamos el jquery ready para que se ejecute nuestro codigo hasta que todo este cargado todo nuestro DOM por que si no se ejecuta en cuanto lo lee.

$(document).ready(function(){
 $("p.nombre").show();
 });

Exercises

Manipulation with css
Find the spans with class ‘trademarked’ and use the CSS function to set the font-size to 90% and the color to #F33.

The source html code to use is the next:


<h1>Safety Information</h1>

<p>
 The information below is <span>critical to survival</span> and you must read it right now. <em>Twice</em>.
 </p>

<h2>Water Landings</h2>
 <p>
 In the event of a water landing, you seat cushion may be used as a floatation device. Despite the smell, we recommend you <em>put your little arms through the straps</em> and hang on for dear life. You might be in the <span>ocean</span> for awhile. I'm not sure if you know this, but we don't have GPS and the plane's homing beacon was designed in the 70s, so you have a better chance that your spouse will spot you on the <span class="trademarked" style="">"Find my iPhone"</span> app than the Coast Guard via a rescue grid.
 <p>

<h2>Exit Procedure</h2>
 <p>
 If you're lucky enough to be seated in an <span class="upsell">exit row</span>, enjoy that awesome leg room. That is unless, of course, we <span>don't land at an airport</span>. In that case, everyone is relying on you to pull the handle and toss the 75-pound door out of the way. <span class="hidden">We're confident that your Level 43 <span class="trademarked" style="">World of Warcraft</span> warrior, despite not helping you develop any actual muscle tone, has at least shown you how heavy things can be lifted.</span>
 </p>
 </p></p>

The solution is:

$('span.trademarked').css("font-size","90%").
 css("color", "#F33");

Using javascript map for multiple values in pairs

$("span.trademarked").css({"font-size" : "90%",
<p dir="ltr">"color" : "#F33",</p>
<p dir="ltr">"font-weight" : "bold"});</p>

Toggling Classes
Find the <SPAN> in the first paragraph and use the toggleClass() function to switch its class between ‘important’ and empty (no class)


<h1>Safety Information</h1>
 <p>
 The information below is <span>critical to survival</span> and you must read it right now. <em>Twice</em>.
 </p>
 <h2>Water Landings</h2>
 <p>
 In the event of a water landing, your seat cushion may be used as a floatation device. Despite the smell, we recommend you <em>put your little arms through the straps</em> and hang on for dear life. You might be in the <span>ocean</span> for awhile. I'm not sure if you know this, but we don't have GPS and the plane's homing beacon was designed in the 70s, so you have a better chance that your spouse will spot you on the <span class="trademarked">"Find my iPhone"</span> app than the Coast Guard via a rescue grid.
 <p>

the solution is

$('p:first > span').toggleClass('important');

this called Bring the text that has the element

$(p#elementid).text()

if we need write html we must use the .html

$(p#elementid).html()

if we want add to the begining of the element text we must use

.prepend("new text")

and adding text at the end of the value text

append("text")

If we want adding new element to the dom after or before some element

.before and after("<h1>add new element")

we can remove from the DOM any element

.remove()

if we want move any element we need remove and add in the position where we want to put

var a = $("span#mielemento").remove();
 $("#donde").before(a);

Exercises

Using the next html code do the next exercises


<h1>Flight</h1>
 <h2>Logistics</h2>
 <table id="logistics">
 <tbody>
 <tr id="time">
 <th>Time</th>
 <td></td>
 </tr>
 <tr id="gate">
 <th>Gate</th>
 <td></td>
 </tr>
 <tr id="arrives">
 <th>Arrives At</th>
 <td></td>
 </tr>
 </tbody>
 </table>
 <h2>Passengers</h2>
 <ul>
 <li>Larry Dimmick</li>
 <li>Freddy Newandyke</li>
 <li>Vic Vega</li>
 </ul>

Use the text() function to change the <H1> to read ‘Flight 428’
The code solution:

$("h1").text("Flight 428");

Fetch the HTML contents of the row with ID “time” store it into a variable named time_row

var time_row = $("#time").html();

Set the <TD> nested under the ‘tr#time’ element to the value ‘<strong>10:15</strong>AM’.

$('#time').html("<td><strong>10:15</strong>AM</td>");

Grab the passenger <UL> list, and use the append() function to add the passengers Eddie Cabot and Mr. Pink to the passenger list. You’ll want to append their names wrapped in <LI> tags so they get attached to the list.
the solution is

$('ul').append('<li>Eddie Cabot</li><li>Mr. Pink</li>');

Fetch the logistics table and use the prepend() function to add a new <TR> that includes a <TH> with the content “Boards At”, and a <TD> with “9:45AM”.

$('#logistics').prepend('<tr><th>Boards At</th><td>9:45AM</td></tr>');

Add a colon to the end of each of the titles in the <TH> cells (Time, Gate, etc). You should only need one line.

$(‘table th’).append(‘:’);

Using the before() function, insert a <P> with the contents ‘Currently Checked-In:’ between the <H2> saying ‘Passengers’ and the <UL>

$('ul').before('<p>Currently Checked-In:</p>');

Now using the after() function, select the :last passenger on the passenger list and add Eddie Cabot and Mr. Pink after him

$('ul li:last').after('<li>Eddie Cabot</li><li></li>');

Larry Dimmick has cancelled his ticket. Remove him from the passenger list.

$('ul li:first').remove();

for example when we need function applied to hover method in li and when de mouse hover out when remove some class we can use the toogleClass to and other way to programming this is calling 2 methods in the hover funcition for example

$(document).ready(function (){
 $('div#plane_features li').hover(
 function (){$(this).addClass('feature_hover');},
 function(){$(this).removeClass('feature_hover');}
 );
 });

The communications department has decided that the ‘tr#gate’ row should come above the ‘tr#time’ row. Make it happen using jQuery.

var temp = $('tr#gate').remove();
 $('tr#time').before(temp);

how to declare a function in jquery

function name(parame){instructions}

function popopuMessage(message){
 alert("escribiste :" + message)
 }

Para ejecutar el codigo cuando el DOM has ready

$(document).ready(function(){
 alert(‘hellooooo’);
 });

one example when you click on p and hide some text

$(document).ready(function(){
 $(‘p’).click(function({
 alert(‘you click on element p’);
 });)
 });

for example if we want to hide a element h2 that is clicked we could use some code like:

$('h2').click(
 function (){
 $(this).hide();
 }
 );

The next example in jquery add style to the elements h2 and looks like a link and when you hover from the element appear the style pointer like link after when you click on the element the element dissapear from the DOM


<html>
 <head>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
 <title>testing codeschool jquery</title>
 <script languajes="javascript">
 $(document).ready(function(){
 $('h2').css('cursor', 'pointer');
 $('h2').click(function(){
 $(this).hide();
 });
 });
 </script>
 </head>
 <body>
 <h1>Flight</h1>
 <h2>Logistics</h2>
 <table id="logistics">
 <tbody>
 <tr id="time">
 <th>Time</th>
 <td></td>
 </tr>
 <tr id="gate">
 <th>Gate</th>
 <td></td>
 </tr>
 <tr id="arrives">
 <th>Arrives At</th>
 <td></td>
 </tr>
 </tbody>
 </table>
 <h2>Passengers</h2>
 <ul>
 <li>Larry Dimmick</li>
 <li>Freddy Newandyke</li>
 <li>Vic Vega</li>
 </ul>
 </body>
 </html>

the next is an example to add and remove some styles at the li elements when mouse hover

<html>
 <head>
 <style type= "text/css">
 li{
 list-style:none;
 }
 .color{
 background-color:yellow;
 }
 </style>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
 <title>testing codeschool jquery</title>
 <script languajes="javascript">
 $(document).ready(function(){
 $('li').hover(function(){
 $(this).toggleClass('color');
 });
 });
 </script>
 </head>
 <body>
 <h1>Flight</h1>
 <h2>Logistics</h2>
 <table id="logistics">
 <tbody>
 <tr id="time">
 <th>Time</th>
 <td></td>
 </tr>
 <tr id="gate">
 <th>Gate</th>
 <td></td>
 </tr>
 <tr id="arrives">
 <th>Arrives At</th>
 <td></td>
 </tr>
 </tbody>
 </table>
 <h2>Passengers</h2>
 <ul>
 <li>Larry Dimmick</li>
 <li>Freddy Newandyke</li>
 <li>Vic Vega</li>
 </ul>
 </body>
 </html>

keyboard events
the next code fire and event when the user touch a keyboard in any letter

$('body').keypress(function(){
 alert('fantastic');
 });

we do too have the event or the keyboard key that is pressed with the next code

$(document).read(function(){
 $(‘body’).keypress(function(event){
 if(event.which == 102 {alert(‘fantastic’)} )
 });
 });

using jquery you can use animation to show or hide for example some elements, for example the next code will hide with a little animation de h1 element you should change that value if you want to apply that animation to another element like : p, h3, h4, li, etc.

$(document).ready(function(){
 $('h1').click(function(){
 $(this).hide('slow');}
 );
 });

Other animation that looks nice is the slideUp (hide) or slideDown(show), you can test the next code:

$(document).read(function(){
 $(‘li’).click(function(){
 $(this).slideUp(‘slow’);
 });
 });

you can use too the slideToogle(‘slow’) to swith between show or hide.

$(‘h2’).slideToggle(‘slow’);

if you want more and interestings animation you can read the jquery animation and test all that has jquery like: fadaIn, fadeOut or many diferents and very nice.

Important Note: all the animation and more jquery have events and we can use that for our purposes , for example event.which is to hand the event in the keyboard keys for example

and there are others events like:

.pageX or pageY to use mouse pointer
.preventDefault to prevent the default action from the browser
.stopPropagation stop the events for triggering other handlers

example of preventdefaul is when we want that the button doesnt display a “#” in the url to this we use prevenDefault()

Exercises from the level 5 and last level in jquery air 1

The Refresh button is setup to call a function named refresh_weight that you need to define.refresh_weight should fetch the current weight from the gauge and display an alert that says ‘Total Weight is currentWeight”.

all the code solution is in one file


<html>
 <head>
 <title>Practice with jquery</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
 <script languajes="javascript">
 $(document).ready(function(){
 $('#refresh').click(refresh_weight);
 function refresh_weight()
 {
 var currentWeight = parseInt($('span#display').text());
 alert('Total Weight is ' + currentWeight); }
 });
 </script>
 <style type="text/css">
 .feature_hover {
 border-left: 5px solid #f68173;
 }
 .feature_selected {
 color: #fff;
 font-weight: bold;
 }
 #altitude {
 width: 180px;
 border: 5px solid #9bb1b1;
 margin: 0 0 0 15px;
 -moz-transform: rotate(8deg);
 -webkit-transform: rotate(8deg);
 transform: rotate(8deg);
 }
 </style>
 </head>
 <body>
 <div id="gross_weight">
 <a href="#" id="weight_up">UP</a>
 <a href="#" id="weight_down">DOWN</a>
 <a href="#" id="refresh">Refresh</a>
 <span id="display">1850</span>
 </div>
 <div id="plane_features">
 <ul>
 <li><a href="#">Seatbelts</a></li>
 <li><a href="#">Cabin Lights</a></li>
 <li><a href="#">Cargo Door</a></li>
 </ul>
 </div>
 <div id="altitude">
 --------
 </div>
 <ul id="nearby_flights">
 </ul>

</body>
 </html>

The UP button is setup to call a function named increment_weight that you need to define.increment_weight should get the current weight, add 50, and update the display.


<html>
 <head>
 <title>Practice with jquery</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
 <script languajes="javascript">
 $(document).ready(function(){
 $('#weight_up').click(increment_weight);
 function increment_weight()
 {
 var currentWeight = parseInt($('span#display').text());
 currentWeight = currentWeight + 50;
 $('span#display').text(currentWeight);
 }
 });
 </script>
 <style type="text/css">
 .feature_hover {
 border-left: 5px solid #f68173;
 }
 .feature_selected {
 color: #fff;
 font-weight: bold;
 }
 #altitude {
 width: 180px;
 border: 5px solid #9bb1b1;
 margin: 0 0 0 15px;
 -moz-transform: rotate(8deg);
 -webkit-transform: rotate(8deg);
 transform: rotate(8deg);
 }
 </style>
 </head>
 <body>
 <div id="gross_weight">
 <a href="#" id="weight_up">UP</a>
 <a href="#" id="weight_down">DOWN</a>
 <a href="#" id="refresh">Refresh</a>
 <span id="display">1850</span>
 </div>
 <div id="plane_features">
 <ul>
 <li><a href="#">Seatbelts</a></li>
 <li><a href="#">Cabin Lights</a></li>
 <li><a href="#">Cargo Door</a></li>
 </ul>
 </div>
 <div id="altitude">
 --------
 </div>
 <ul id="nearby_flights">
 </ul>
 </body>
 </html>

Attach a click event listener to the DOWN button that fetches the gauge’s current weight, subtracts 50, and updates the display. Make sure to use preventDefault() to prevent the browser from following the link.


<html>
 <head>
 <title>Practice with jquery</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
 <script languajes="javascript">
 $(document).ready(function(){
 $('#weight_down').click(function(event){
 event.preventDefault();
 var currentWeight = parseInt($('span#display').text());
 currentWeight = currentWeight - 50;
 $('span#display').text(currentWeight);
 });
 });
 </script>
 <style type="text/css">
 .feature_hover {
 border-left: 5px solid #f68173;
 }
 .feature_selected {
 color: #fff;
 font-weight: bold;
 }
 #altitude {
 width: 180px;
 border: 5px solid #9bb1b1;
 margin: 0 0 0 15px;
 -moz-transform: rotate(8deg);
 -webkit-transform: rotate(8deg);
 transform: rotate(8deg);
 }
 </style>
 </head>
 <body>
 <div id="gross_weight">
 <a href="#" id="weight_up">UP</a>
 <a href="#" id="weight_down">DOWN</a>
 <a href="#" id="refresh">Refresh</a>
 <span id="display">1850</span>
 </div>
 <div id="plane_features">
 <ul>
 <li><a href="#">Seatbelts</a></li>
 <li><a href="#">Cabin Lights</a></li>
 <li><a href="#">Cargo Door</a></li>
 </ul>
 </div>
 <div id="altitude">
 --------
 </div>
 <ul id="nearby_flights">
 </ul>

</body>
 </html>

Attach a hover event to ‘div#plane_features li’. When the elements are hovered over add the class named ‘feature_hover’ using addClass(), then remove it when they hover out using removeClass().


<html>
 <head>
 <title>Practice with jquery</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
 <script languajes="javascript">
 $(document).ready(function (){
 $('div#plane_features li').hover(
 function (){$(this).addClass('feature_hover');},
 function(){$(this).removeClass('feature_hover');}
 );
 });
 </script>
 <style type="text/css">
 .feature_hover {
 border-left: 5px solid #f68173;
 }
 .feature_selected {
 color: #fff;
 font-weight: bold;
 }
 #altitude {
 width: 180px;
 border: 5px solid #9bb1b1;
 margin: 0 0 0 15px;
 -moz-transform: rotate(8deg);
 -webkit-transform: rotate(8deg);
 transform: rotate(8deg);
 }
 </style>
 </head>
 <body>
 <div id="gross_weight">
 <a href="#" id="weight_up">UP</a>
 <a href="#" id="weight_down">DOWN</a>
 <a href="#" id="refresh">Refresh</a>
 <span id="display">1850</span>
 </div>
 <div id="plane_features">
 <ul>
 <li><a href="#">Seatbelts</a></li>
 <li><a href="#">Cabin Lights</a></li>
 <li><a href="#">Cargo Door</a></li>
 </ul>
 </div>
 <div id="altitude">
 --------
 </div>
 <ul id="nearby_flights">
 </ul>

</body>
 </html>

Refactor the code below to use toggleClass() and pass only one function to the hover listener


<html>
 <head>
 <title>Practice with jquery</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
 <script languajes="javascript">
 $(document).ready(function(){
 $('div#plane_features li').hover(function (){
 $(this).toggleClass('feature_hover');
 });
 });
 </script>
 <style type="text/css">
 .feature_hover {
 border-left: 5px solid #f68173;
 }
 .feature_selected {
 color: #fff;
 font-weight: bold;
 }
 #altitude {
 width: 180px;
 border: 5px solid #9bb1b1;
 margin: 0 0 0 15px;
 -moz-transform: rotate(8deg);
 -webkit-transform: rotate(8deg);
 transform: rotate(8deg);
 }
 </style>
 </head>
 <body>
 <div id="gross_weight">
 <a href="#" id="weight_up">UP</a>
 <a href="#" id="weight_down">DOWN</a>
 <a href="#" id="refresh">Refresh</a>
 <span id="display">1850</span>
 </div>
 <div id="plane_features">
 <ul>
 <li><a href="#">Seatbelts</a></li>
 <li><a href="#">Cabin Lights</a></li>
 <li><a href="#">Cargo Door</a></li>
 </ul>
 </div>
 <div id="altitude">
 --------
 </div>
 <ul id="nearby_flights">
 </ul>

</body>
 </html>

Add a click event listener on each of the links in the plane features list. When clicked each should toggle the class ‘feature_selected’. Remember to use event.preventDefault to stop the browser from following the link


<html>
 <head>
 <title>Practice with jquery</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
 <script languajes="javascript">
 $(document).ready(function(){
 $('div#plane_features li').click(function(event){
 event.preventDefault();
 $(this).toggleClass('feature_selected');
 });

});
 </script>
 <style type="text/css">
 .feature_hover {
 border-left: 5px solid #f68173;
 }
 .feature_selected {
 color: #fff;
 font-weight: bold;
 }
 #altitude {
 width: 180px;
 border: 5px solid #9bb1b1;
 margin: 0 0 0 15px;
 -moz-transform: rotate(8deg);
 -webkit-transform: rotate(8deg);
 transform: rotate(8deg);
 }
 </style>
 </head>
 <body>
 <div id="gross_weight">
 <a href="#" id="weight_up">UP</a>
 <a href="#" id="weight_down">DOWN</a>
 <a href="#" id="refresh">Refresh</a>
 <span id="display">1850</span>
 </div>
 <div id="plane_features">
 <ul>
 <li><a href="#">Seatbelts</a></li>
 <li><a href="#">Cabin Lights</a></li>
 <li><a href="#">Cargo Door</a></li>
 </ul>
 </div>
 <div id="altitude">
 --------
 </div>
 <ul id="nearby_flights">
 </ul>

</body>
 </html>

Add the keydown event listener so when “s” (key_code 83) is pressed it toggles the “feature_selected” class on the Seatbelts link li.


<html>
 <head>
 <title>Practice with jquery</title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
 <script languajes="javascript">
 $(document).ready(function(){
 $(document).keydown(function(event){
 if(event.which == 83){
 $('div#plane_features li:first').toggleClass('feature_selected');
 }
 });
 });
 </script>
 <style type="text/css">
 .feature_hover {
 border-left: 5px solid #f68173;
 }
 .feature_selected {
 color: #fff;
 font-weight: bold;
 }
 #altitude {
 width: 180px;
 border: 5px solid #9bb1b1;
 margin: 0 0 0 15px;
 -moz-transform: rotate(8deg);
 -webkit-transform: rotate(8deg);
 transform: rotate(8deg);
 }
 </style>
 </head>
 <body>
 <div id="gross_weight">
 <a href="#" id="weight_up">UP</a>
 <a href="#" id="weight_down">DOWN</a>
 <a href="#" id="refresh">Refresh</a>
 <span id="display">1850</span>
 </div>
 <div id="plane_features">
 <ul>
 <li><a href="#">Seatbelts</a></li>
 <li><a href="#">Cabin Lights</a></li>
 <li><a href="#">Cargo Door</a></li>
 </ul>
 </div>
 <div id="altitude">
 --------
 </div>
 <ul id="nearby_flights">
 </ul>

</body>
 </html>

Find the <DIV> element with id = altitude and hide it using the ‘slow’ effect.

$(document).ready(function(){
 $('div#altitude').hide('slow');
 });

Attach a click event listener to the Refresh button that uses ajax to load ‘/nearby_flights’ and places the response into the Nearby Flights list. Don’t forget to prevent the default link behavior.

No Comments

Post A Comment