Saturday, April 6, 2013

jQuery's on function tutorial

This tutorial show how to work with table element. It uses jQuery function on() to highlight both tables. The one that will be inserted in page DOM after AJAX call to file ajax.php and the other table that is part of initial DOM.

<!DOCTYPE html>
<html>
<head>
<title>.on()</title>
<meta charset="utf-8" />
<script src="jquery.min.js"></script>
<style>
.zebra { 
  background-color: #dddddd;
  color: #666666;
}
.zebrahover {
  background-color: #FFFACD;
}
</style>
<script>
$(document).ready(function(){
    $('table tbody tr:even').addClass('zebra');
    $('a').click(function() {
        sub();
    });
});
function sub() {
  $.ajax({
                type: "POST",
                url: "ajax.php",
                timeout:5000,
                beforeSend: function(xhr){
                    //$('#load').show();
                },
                success: function(response){
                    $('#response').append(response);
                    //$('#rows div:last').fadeOut(10).fadeIn(2000);
                    //uncomment for debugging purposes
                    //alert(response);
                },
                error: function(jqXHR) {
                   alert ('From error:' + jqXHR.status + ' ' +jqXHR.statusText);
                },
                complete: function(jqXHR, textStatus){
                    //uncomment for debugging purposes
                    //alert ('From complete:' + jqXHR.status + ' ' +jqXHR.statusText + ' ' + textStatus);
                    //$('#load').hide();
     }
  });
 return false;
 }
    

$(document).on("mouseover","tbody tr", function(){
    $(this).addClass('zebrahover');
});

$(document).on("mouseout","tbody tr", function(){
    $(this).removeClass('zebrahover');
});
</script>
</head>
<body>
<div id="response">
</div>
<a href="#">Make table sa AJAX call</a>
<hr/>
        <table class="data">
          <thead>
            <tr>
              <th>ID</th>
              <th>Name</th>
              <th>Occupation</th>
              <th>Approx. Location</th>
              <th>Price</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>203A</td>
              <td>Johny Stardust (<a href="bio.pdf">bio</a>)</td>
              <td>Front-man</td>
              <td>Los Angeles</td>
              <td>$39.95</td>
            </tr>
            <tr>
              <td>141B</td>
              <td>Beau Dandy (<a href="img.jpg">pic</a>,<a href="bio.pdf">bio</a>)</td>
              <td>Singer</td>
              <td>New York</td>
              <td>$39.95</td>
            </tr>
          </tbody>
        </table>
</body>
</html>

No comments:

Post a Comment