Tribal Knowledge Hub

Technical discoveries, solutions and musings from a long time IT professional.

Archive for the ‘JavaScript’ Category

A Simple jQuery Image Rotater

leave a comment

leave a comment

Recently I was looking to add a collection of rotating images to my website, so I searched for an image rotater using jQuery. I found a number of very sophisticated libraries designed to rotate images, create slideshows and display fancy transitions. Any one of these would have met my needs. What I did not find was a simple bare-bonesjQuery example that I could use on my web site and enhance as I saw fit. So, I decided to build one form scratch. This example is simple enough that anyone with any jQuery experience at all can understand it. Hopefully, the explanation is clear enough that anyone can incorporate it into their own web site or use it as a starting point to learn jQuery.

Because this this blog is built on  a framework that already uses jQuery, the image rotater can’s be directly embedded in this post. You can access an example by clicking on the image or at http://www.dchung.com/test/rotate.

Let’s look at the source code. The Javascript first then the HTML5:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<script src="scripts/jquery/1.8.3/jquery.min.js"></script>
<script>  

  // define array of image paths (src) and captions (figcaption)
  var images = [
      {src:"lighthouse.jpg", figcaption:"Peggy's Cove, Nova Scotia"},
      {src:"newyork.jpg",    figcaption:"New York before 9/11"},
      {src:"tetons.jpg",     figcaption:"Mormon Row, the Tetons"},
      {src:"tuileries.jpg",  figcaption:"Tuileries Garden, Paris"}
  ];

  // execute this anonymous function when the DOM has been loaded in memory
  $(document).ready(

    function() {

      // index to select item in array
      var i=0;

      // use the jQuery function ($) to select the <img> and <figcaption> by id
      var img = $('#rotate-img');
      var fig = $('#rotate-caption')

      // set the initial src and figcaption values 
      img.attr("src", images[i].src);
      fig.html(images[i].figcaption);

      // advance to next image 
      i++;

      // setInterval takes to parameters, a callback and an interval 
      window.setInterval(function() {

          // reset the index to 0 if past the end
          if( i >= images.length ) { 
            i = 0; 
          }

          // hide the current image then fade the new image in and set
          // the new caption 
          img.hide();
          img.attr("src", images[i].src).fadeIn('slow');
          fig.html(images[i].figcaption);      

          // advance to next image
          ++i;          
        },

        // set the image time to 5000ms
        5000 
      )
    }

  );
</script>

 

Notice that this example uses the ever-present closure. Notice that the values: i, img and fig are defined in the ready() function. The values  are used in the anonymous function called by the setInterval() function. The setInterval() function is called by the ready() function. By the time the anonymous function is called, both ready() and setInterval() have completed. The fact that the anonymous function can still access i, img and fig is a result of the closure.

 

60
61
62
63
<figure>
  <img id="rotate-img" width="250px" alt=""/>
  <figcaption id="rotate-caption"></figcaption>
</figure>

 

The associated HTML5 is shown above. Notice that the src attribute and the <figcaption> values are specified in the jQuery not the HTML5.

Feel free to use this code on your own site or use it as a starting point. There are several other features that could be added like different transitions, radomization … and more.

Written by Dave

December 10th, 2012 at 12:17 am

Posted in JavaScript,jQuery

Getting ‘Closure’

one comment

I have been a Java developer since 1995, before that I worked in C++.  So my language background is primarily statically-typed and object oriented. In the last several years, I’ve been involved in a number of projects that use JavaScript. I’ve come to recognize that JavaScript is a very powerful language in its own right — but it is dramatically different from the languages that I am used to. One of the features of JavaScript that was a mystery to me is closure.

Closure has no direct equivalent in my native language Java so it took a great deal of reading and experimentation for me to come to grips with this concept. The simplest description I can give is this.

In a closure a variable declared in an outer function is visible to an inner function even if the inner function’s lifecycle is longer than that of the outer function.

Here is an example using the Apache Cordova (PhoneGap) API. The phone Cordova API allows you to package HTML5/CSS/JavaScript applications natively for a number of mobile platforms. It also provides a JavaScript API to wrap many of the native device features like the accelerometer. This example shows a closure.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function startWatch() {

  var previousReading = { x: null, y: null, z: null };

  navigator.accelerometer.watchAcceleration(

    function (acceleration) {
      // use previousReading value here
    },
    onError, 
    { frequency: 500 }
 );

}

 

In this example the startWatch() function declares a variable previousReading and sets its x, y and z members to null. The three values will be used to represent acceleration in meters per second squared. The function then calls navigator.accelerometer.watchAcceleration(), passing in an anonymous callback for success. The anonymous callback defined on line 7 in the source code will be called at a rate of once every 500ms and it will compare the current acceleration with previousReading then update previousReading with the current acceleration.

The code is relatively straightforward except for one important detail previousReading was declared in the scope of the outer function startWatch. But the anonymous inner function (on line 7) will be called repeatedly even after the outer function is out of scope! What happens here is that the inner function keeps a reference to any values in the outer scope that it will need when it is invoked.

For those of you who are Java programmers, don’t think you are immune from this discussion. Closures are on the proposed feature list for JDK 8.

Written by Dave

November 3rd, 2012 at 5:01 pm

Posted in JavaScript