Tuesday 10 February 2015

Using Font Awesome icons and jQuery to show form loading in Twitter Bootstrap page

Font Awesome is a really useful tool for adding icons to your website. It also comes with animated icons which can be used to show when your form is waiting for a response. In the example below, I have created a basic Twitter Bootstrap page. The page has a form. When the form is submitted, there is a delay in its response. During the delay, I use jQuery to show a Font Awesome animated icon.
First the Twitter Bootstrap page with the differences in red:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Font Awesome Animated Icons</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">   
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
  <i class="fa fa-circle-o-notch fa-spin"></i>  
  <form action="response.php" method="POST">
    <input type="text" name="yourname" id="yourname" placeholder="Enter your name" />
    <button type="submit">Submit</button>
  </form>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
  <script>
  (function()
  {
    var thisForm = $('form');
    var i = $('i');
    i.hide();
    thisForm.submit(function()
    {
      i.show();
      thisForm.hide();
      $.post(thisForm.attr('action'),thisForm.serialize(), 
      function(data)
      {
        thisForm.empty().html(data);
        i.hide();
        thisForm.show();
      });  
      return false;
    });
  })();
  </script>
  </body>
</html>
Now my response.php
<?php
sleep(2);
echo 'Hello '.$_POST['yourname'];
?>

No comments:

Post a Comment