slides and bubbles (jquery event delegation)

I wanted to improve my slideshow with image preloading. What I wanted was something that resembles a queue for preloading.

On a blog I found a piece by Rebecca Murphey, she seems a very smart programmer. I picked up on the idea of triggering events, then read some remarks on binding data to an element, and on event delegation.

Being a noob, I concocted thus :

Each element I use to run the ‘slideshow’ has three basic functions,

  • AjaxLoadImages : loads the xml data ( image urls) into $(elem).data()
  • displayImage : replaces the css background-image url
  • preLoad : creates an img element in the document with the image url as source, to force the browser to download the picture so once I put it in the css background the image file is already downloaded, that stops the flickering

The latter two run on a timer, more about that later on in the post.

With bind(), I tie the event handler function to an element, and can use my own events. I can delegate the handling of events up the dom tree by leaving the handler of the lower elements void and binding a handler with the same name to a higher level element, like body.

  1. $("div").bind('preLoad', function(e) {});
  2. $("div").bind('displayImage', function(e){});
  3. $("div").bind('AjaxLoadImages', function(e){});

In ‘bubbling up’ the element data of the element where the event was triggered is sent along. I can access that elements .data() (with my image list etc.) through the generic $(event.target) object.

  1. //AjaxLoadImages is a http-get that retrieves
  2. //an xml file, and adds the links in it to the .data()
  3. //attribute of the div
  4.  
  5. //I trigger the event on the div, which is handed upward
  6. //to this function, with the div as 'target'
  7.  
  8. $("body").bind('AjaxLoadImages', function(e, fname) {
  9.  var target = $(e.target);
  10.  
  11.  $.get(fname, {}, function(xml)  {
  12.   var counter = 0;
  13.   $('entry', xml).each(function(i) {
  14.        counter++;
  15.                      //key = (x + counter)
  16. $(e.target).data(('x'+counter).toString(), $(this).find("link").text());
  17.   });
  18.  
  19. //some general data
  20.   $(e.target).data("preload", "0");
  21.   $(e.target).data("currentimage", "1");
  22.   $(e.target).data("countimage", counter.toString());
  23.  });
  24. });
  25.  
  26.  
  27. //displayImage retrieves the 'currentimage' value
  28. //which, with an added X,
  29. //is the key of the imageurl in the .data() element
  30. //(which is key=>value array)
  31.  
  32. //Once I have it, I can replace the background image url
  33. //in the css
  34.  
  35. $("body").bind('displayImage', function(e) {
  36.  var target = $(e.target);
  37.         $(e.target).css('background-image', 'url(' + $(e.target).data(('x'+ target.data("currentimage") ).toString()) +  ')');
  38. });  
  39.  
  40. //preload does the same trick, with the source attribute
  41. //of an image I add to force the browser to preload
  42. $("body").bind('preLoad', function(e) {
  43.     $('<img />').attr({
  44.     src: $(e.target).data(('x' + $(e.target).data("currentimage")).toString()) });
  45. });

the xml file is plain :
<?xml version=”1.0″ encoding=”UTF-8″?>
<xmlslides>
<entry>
<link>http://www.juust.org/slides/one.png</link>
</entry>
<entry>
<link>http://www.juust.org/slides/two.png</link>
</entry>

</xmlslides>

That sets up the basic data and functions for the div elements.

Now to make it run.

Timing, even with the SetInterval method, was gonna be a pain as it seems I can not tie SetInterval  to an element. Luckily (blair mitchelmore?) was so kind as to write a jQuery plugin to handle multiple timers.

With that, I can write one event handler on body level that assigns each element that comes bubbling up a function on a timer interval to handle the display and preloading, as if it were a loop.

  1. //binding the event with void handler
  2. $("div").bind('ScheduleSlides', function(e){});
  3.  
  4. ///…then binding the actual event handler to body,
  5. //param holds the interval
  6. $('body').bind("ScheduleSlides", function(e, param) {
  7.  
  8.  var target = $(e.target);
  9.  
  10. //runs a function on set intervals for the target element
  11.  target.everyTime(param, function(i) {
  12.  
  13. //display the current image by triggering displayImage,
  14. //which bubbles up to the body event handler
  15.   var imgcount = target.data("currentimage");
  16.   target.trigger('displayImage');
  17.  
  18. //increase the functions internal counter
  19.   imgcount++;
  20.  
  21. //set currentimage to the increased counter
  22.                 target.data("currentimage", (imgcount).toString());
  23.  
  24. //if at the end of the image list,
  25. //reset currentimage
  26. //and end preloading
  27.   if( target.data("currentimage") == target.data("countimage") ) {
  28.    target.data("preload", "1");
  29.    target.data("currentimage", "1");
  30.   };
  31.  
  32. //preload the new image if necessary
  33.   if(target.data("preload") == "0") {
  34.    target.trigger('preLoad');
  35.   };
  36.  });
  37. });

All that remains is to load an xml file and trigger the scheduling…

  1. $("#dia_show").trigger(
  2.  "AjaxLoadImages",
  3.  "http://www.juust.org/slides/a.xml"
  4. );
  5. $("#dia_show").trigger('ScheduleSlides', 1000);

and another one…

  1. $("#dia_show_2").trigger(
  2.  "AjaxLoadImages",
  3.  "http://www.juust.org/slides/b.xml"
  4.     );
  5. $("#dia_show_2").trigger('ScheduleSlides', 2000);

I really wonder why I wrote it that way, but it seems to work without the flickering bit and without having to code the links in css or in the source.

I put the test page and the source of it on the server.

I read some remarks on other blogs that after adding 14 img elements IE throws a stack overflow, I haven’t looked into that.

faking links & dblclick search

Being a noob at jquery, I was very satisfied with these two : the first is a one liner to search the blog when someone doubleclicks on a word, the second is an easy fake anchor.

double click search

If you double click (in some browsers?) you select the word under the cursor. Bind the double click event of a paragraph element to a function that uses the standard worpdress search, using bloginfo(‘home’) to get the home url, with the selected text as ?s= search parameter, and relocates to the search result page.

  1. jQuery(document).ready(function() {
  2.  jQuery('p').bind('dblclick', function(e){
  3.   window.location = '&lt;?php bloginfo('home'); ?&gt;/?s='+getSelectedText();
  4.     });
  5.  
  6. });
  7.  
  8. function getSelectedText(){
  9.     if(window.getSelection){
  10.         return window.getSelection().toString();
  11.     }
  12.     else if(document.getSelection){
  13.         return document.getSelection();
  14.     }
  15.     else if(document.selection){
  16.         return document.selection.createRange().text;
  17.     }
  18. }

fake a link

You can also fake a hyperlink, makes seo life easier.

Any surplus inline element will do, in this case the dfn tag, as most have the title attribute that I use to store the url  :

<dfn title="http://elgoog.rb-hosting.de/index.cgi?dir=/Top/News/&amp;page=Satire/">hyperlink</dfn>

Style the dfn element with a bit of css :

  1. dfn {
  2.   color: blue;
  3.  textdecoration: underline;
  4.  fontsize: 14px;
  5. }

…and it looks like a hyperlink, add some jQuery to bind a click event on the dfn element to a function that jumps to the title attribute.

  1. jQuery(document).ready(function() {
  2.  
  3.  jQuery('dfn').bind('click', function(e){
  4.   window.location = jQuery(this).attr('title');
  5.     });
  6. });

…and we have the link that search engines do not index as a link, but it does work.

 

masked slideshow – jquery & wordpress

I agreed to make a wordpress template for a friends’ site. As extra feature they wanted a slide show in the sidebar with a half transparent mask.

I trolloped around the net a little and this seems the most basic sidebar slideshow :

 
 

I make a new 240×240 image in photoshop and use a radial gradient from transparent to white, making the center of the picture transparent, and export it as ‘mask.png’, 24bit.

In my sidebar_left.php I make three divs, one is the container dia_frame,

the other two are the overlay and the slideshow div.

<div id="dia_frame">
      <div id="dia_show"></div>
       <div id="dia_overlay"></div>
</div>

I give he frame the z-order 90, the mask the z-order 92, the slideshow is z-order 91. That makes sure the overlay is rendered on top of the slideshow.

Both the overlay and show div are relative positioned. 

 

  1. #sidebar_left #dia_frame {
  2.   width: 240px;
  3.   minheight : 240px;
  4.   _height : 240px;
  5.   clear: both;
  6.   zindex: 90;
  7. }
  8.  
  9. #sidebar_left #dia_frame #dia_show {
  10.  width: 240px;
  11.  minheight: 240px;
  12.  _height: 240px;
  13.  position: relative;
  14.  float: right;
  15.         zindex: 91;
  16. }
  17.  
  18. #sidebar_left #dia_frame #dia_overlay {
  19.  width: 240px;
  20.  position : relative;
  21.  background: url(images/mask.png) norepeat;
  22.    minheight : 240px;
  23.   _height : 240px;
  24.  zindex: 92;
  25. }

That sets up the xhtml and css frame in the side bar. Then I go make the slideshow. I grab some graphics of flowers and store them in the themes images folder.

With jQuery in header.php I make an array containing the image urls, and with a timer, cycle the slideshow background graphics :

  1. jQuery(document).ready(function() {
  2. var allImgs = [];
  3.  
  4.  allImgs[0] = "/images/one.png";
  5.  allImgs[1] = "/images/two.png";
  6.  allImgs[2] = "/images/three.png";
  7.  allImgs[3] = "/images/four.png";
  8.  allImgs[4] = "/images/five.png";
  9.  
  10.     var currentSlide = 0;
  11.  
  12.   jQuery.mynamespace = {};
  13.  jQuery.mynamespace.counter = currentSlide;
  14.  jQuery.mynamespace.imgs= allImgs;
  15.  
  16.     function imgRotate() {
  17.  
  18.         jQuery('#dia_show').css('background', 'url(' + jQuery.mynamespace.imgs[jQuery.mynamespace.counter] +  ') no-repeat right');
  19.   jQuery.mynamespace.counter++;
  20.   if(jQuery.mynamespace.counter > 4) {
  21.    jQuery.mynamespace.counter = 0;
  22.   };
  23.     }
  24.  
  25.     setInterval(imgRotate, 2000);
  26.  
  27. });

 

That’s the basic setup

IE5 and IE6 dont support PNG transparency, so for these there are a number of workarounds. supersleight by drew mclellan is reprogrammed to work with jQuery, for wordpress that seems the best option.