Dec 21, 2011

Basic JQuery Tutorial

I have been playing with JQuery and I am falling in love with it. It offers you a simple way to add powerful features to any website; I don't think there is anything out there that compares. If there is, please let me know so I can try it out!

Anyway, the purpose of this post is to offer a brief code example that uses JQuery to manipulate the DOM of your website. I also provided some references that I used, so if you want to do some exploring just click away!

What you need:

  • The JQuery framework for JavaScript
  • Some knowledge of HTML, CSS and Javascript
  • A web-server such as Apache or nginx

Summary:

This post will show a couple of quick 'Hello World' examples, followed by a quick overview of some interesting functions available in JQuery.

Hello world: Example 1

The following code includes HTML comments to explain the code:

<html>
    <head>
       <title>jQuery Hello World</title>

        <!-- Include the JQuery Library code... JQuery will not work without this -->

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
    </head>

    <!-- Our JQuery function. This will search for #flag and inject the Hello world text -->

    <script type="text/javascript">
        $(document).ready(function(){
            $("#flag").html("Hello World !! (display due to jQuery)");
        });

    </script>
 

    <body>
        <!-- Note that this is empty, but upon execution will contain text -->
        <div id="flag">
        </div>
 
    </body>
</html>



Hello world: Example 2

This Hello World example differs slightly in that it now uses an alert box to display the text:

<html>
    <head> 
        <title>jQuery Hello World</title> 
        <!-- Include the JQuery Library code... JQuery will not work without this -->            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script> 
    </head>
 
    <!-- Our JQuery function. This will output a text box on the click event -->
    <script type="text/javascript"> 
        $(document).ready(function(){
             $("#cl").click(function(){
                 alert("HELLO WORLD!"); 
            });
         });
     </script>
 
    <body> 
        <button id="cl">Click Me</button> 
    </body>
</html>



Editing and manipulating JQuery elements

This code will output the size of any div element that is of the "change" class:

alert($("div.change p").size());
// This will count any <p> element within <div class="change"></div>

This will slide a <p class="first"> element up or down to hide/show it when called:

$("div.change p.first:hidden").slideDown("slow");
$("div.change p.first:visible").slideUp("slow");

This will instantly change the CSS code of any <em> element within <div class="change"></div>:

$("div.change em").css({color:"#993300", fontWeight:"bold"});

References:

Dec 15, 2011

Jquery Slideshow

This was a little feature I wrote up for a website that wanted a slide-show. The code allows you to adjust some parameters and should be production ready, although it can definitely be optimised better. Feel free to post edits or comments!

What you need:

  • The JQuery framework for JavaScript
  • Some knowledge of HTML, CSS and Javascript
  • A web-server such as Apache or nginx (or use a hosting service)

Summary:

We create an JavaScript object using JQuery and set up some parameters such as fade-in time and intervals between switching the images. The object will then find all items tagged as 'rotating-item' and loop through each image (according to our parameter set).

The JavaScript/JQuery Code

This should be all the code you will need for the moment; save this as 'slideshow.js' in a place your server can access. The code comments should be adequate, but just in case here are some notes:
  • The function $(window).load() means that the following JavaScript code will execute once the HTML/CSS page has finished loading the elements
  • In JQuery, $('..') is a query that searches the HTML/CSS DOM (Document Object Model) for elements that matches the query. So $('.rotating-item') searches the HTML document for any element that is of the class 'rotating-item;
/**
  * @author AlmightyOlive
  */
$(window).load(function() { //start after HTML, images have loaded
     var InfiniteRotator =
     {
         init: function()
         {
             //initial fade-in time (in milliseconds)
             var initialFadeIn = 1000;

             //interval between items (in milliseconds) 
             var itemInterval = 5000;

             //cross-fade time (in milliseconds)
              var fadeTime = 2500;
             //count number of items
             var numberOfItems = $('.rotating-item').length;

             //set current item
             var currentItem = 0;

             //show first item
             $('.rotating-item').eq(currentItem).fadeIn(initialFadeIn);

             //loop through the items
             var infiniteLoop = setInterval(function(){
                 $('.rotating-item').eq(currentItem).fadeOut(fadeTime);

                 if(currentItem == numberOfItems -1){
                     currentItem = 0;
                 }else{
                     currentItem++;
                 }

                 $('.rotating-item').eq(currentItem).fadeIn(initialFadeIn);
             }, itemInterval);
         }
     };
     InfiniteRotator.init();
});

The CSS

This code defines the look and feel of the elements. Take care when changing these defaults as doing so may result in the slideshow not being displayed at all. I suggest you copy the code as is (although change the width and height parameters to the size of your largest image), test it out and then make your changes. Also, make sure you keep the display: none; property of the rotating-item element!

#rotating-item-wrapper
{
 position: relative;
 width: 768px;
 height: 512px;
}

.rotating-item 
{
 display: none;
 position: absolute;
 top: 0px;
 left: 0px; 
}
 

The HTML

The final part of the code is the HTML structure. Make sure you include the JQuery API and your JavaScript code (insert the following line inside the ... element of your document)!

<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript' src='./slideshow.js'></script>


Now you just place the following code wherever you want the slideshow to appear. Just to clarify; the wrapper element sets up the position and size of the frame that the images will be displayed in, so all the images MUST be placed within the wrapper if you want it displayed properly.

<div id="rotating-item-wrapper">
<img src"./img1.jpg" alt="" class="rotating-item" />
<img src"./img2.jpg" alt="" class="rotating-item" />
</div>


Hope you find this code useful. Enjoy!