Showing posts with label Images. Show all posts
Showing posts with label Images. Show all posts

Saturday, December 17, 2011

All Images Loaded (imagesLoaded)

*NOTE* this code causes infinite loops in IE with image load errors, so I improved and turned this into a real plugin and hosted it on github.


A little jQuery function that checks if all images are loaded. If they all are, the callback function is called. Check out the latest version in this gist.

Script below:
/*
 Check if all images are loaded
 - Callback occurs when all images are loaded
 - image load errors are ignored (complete will be true)
 - Use:
   $('.wrap img').imagesLoaded(function(){
     alert('all images loaded');
   });
*/

jQuery.fn.extend({
  imagesLoaded: function( callback ) {
    var i, c = true, t = this, l = t.length;
    for ( i = 0; i < l; i++ ) {
      if (this[i].tagName === "IMG") {
        c = (c && this[i].complete && this[i].height !== 0);
      }
    }
    if (c) {
      if (typeof callback === "function") { callback(); }
    } else {
      setTimeout(function(){
        jQuery(t).imagesLoaded( callback );
      }, 200);
    }
  }
});

Use it as follows:
$(function(){
  $('.wrap img').imagesLoaded(function(){
    alert('all images loaded');
  });
});

Tuesday, April 19, 2011

Vertical Parallax Effect for the Entire Page

I found a game site (Elder Scrolls) that has a really cool vertical scrolling effect that I wanted to duplicate, but it only works in webkit browsers. I didn't make it into a plugin, but instead made this tutorial, because if you understand the basics, you can add more background images or use CSS3 to add multiple background images.



This is a screen shot of the web page while it is at the top. Note the location of the building tower top is near the top of the logo that is under "Generic".


This screen shot shows how the top of "Box 1" is now above the building tower. Blocks in the foreground move slightly faster than the background image.


Here is the final demo of the vertical scrolling effect (see it as a full page).

How it's done

The Images
This effect uses two background images. The top image (bg1.jpg, 1920x1080 pixels) fades to solid black on its bottom edge.

It's made to be a bit blurry, but you can duplicate the game site's background image by keeping the foreground sharp and the background blurry... it's a cooler effect ;)
 

The second background image (bgtile.jpg, 963x1641 pixels) is added as a background image that appears under the above top image. The css is adjusted so that the top of this image appears below the top image so that you don't see a straight black line cut through the top.

This image is blurry and mostly black, it fades to solid black at the edges, with a rock-like texture. It makes the vertical parallax scroll very subtle, so you may want to adjust it as desired.


The other two images that are used are the title/logo image (title.png, 400x300 pixels).



And the box background (bg-black-55.png, 20x20 pixels) which is a png file of solid black with a 55% opacity.


The Markup
This is very basic HTML markup. The body contains the repeating background tile image (bgtile.jpg). A wrapper is immediately inside the body which contains the top background image (bg1.jpg). These two images could be combined in the body tag if you use css3; then you could use the wrapper for additional images. The Header contains the logo (title.png) and each block of content has the box background image (bg-black-55.png) applied. Fill in the "div.content" block with whatever you want.
<body> <!-- contains repeated background image -->
<div id="wrapper"> <!-- contains top image -->

<div id="header"></div> <!-- contains the page title image -->

 <div class="block"> <!-- contains 55% opacity background image -->
  <h3>Block 1</h3>
  <div class="content">Content 1.</div>
 </div>

 <div class="block"> <!-- contains 55% opacity background image -->
  <h3>Block 2</h3>
  <div class="content">Content 2.</div>
 </div>

 <div class="block"> <!-- contains 55% opacity background image -->
  <h3>Block 3</h3>
  <div class="content">Content 3.</div>
 </div>

 <div class="block"> <!-- contains 55% opacity background image -->
  <h3>Block 4</h3>
  <div class="content">Content 4.</div>
 </div>

 <div class="block"> <!-- contains 55% opacity background image -->
  <h3>Block 5</h3>
  <div class="content">Content 5.</div>
 </div>

</div>

</body>

The CSS
The CSS below doesn't have a lot of comments, but the important parts to focus on are the main background image positions.
body {background: #333; color: #ddd;}
a:link { color: #ddd; }
a:hover { text-decoration: underline; }
a:visited,a:active { color: #999; }

/* Tiled background image */
body {
 margin: 0;
 padding: 0;
 /* Use height of header image for top position */
 background: #000 url(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg7fBBufKSR47RD9ESntGl85BAeIpSrYvQv9JzbnrK6i-jYhidex39OZ6_4lDD3EXxKv7I3pd4XWnOUyzax9evROh_GLcIfkX8I3vQO6Y1FuA0KruXm33MggzrqsSVR91iOFJvTZylHFiM/s200/bgtile.jpg) left 1080px repeat-y;
}
/* Top background image (1920x1200) */
#wrapper {
 position: relative;
 top: 0;
 left: 0;
 height: 100%;
 width: 100%;
 background: url(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizCx7mqIPhdQ10Xgmieaa4PTAR5suXGEi7ezqiiL5G_h0yFCXhvibhec2mTLDBXGnkTbWC-LeqbKT634Ppt40wdciHfm6fq7QuY5v1pDeWJ6nvzv8T7bj3mrOBd-oxDGuhJmIc5daHeA0/s200/bg1.jpg) center top repeat-x;
 z-index: 100;
}
/* Page Title image */
#header {
 height: 350px;
 background: url(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEipx4m-HiIJ90H0QrnLtd5DHyP1J29su3Sn1McbkRcQrKu934Z6WjSGM7stMU5RB97-ZVrQ4_zHV7r81NuIXWmTdXIkoNyuTCj19sGjfxGDkLfOpL0Ou_1jE4xWB-NS5WnP_svT4OkqhbQ/s200/title.png) center 40px no-repeat;
}
/* Content Block with 55% opacity background image */
.block {
 width: 400px;
 height: 500px;
 margin: 20px auto;
 border: #333 1px solid;
 padding: 20px;
 background: url(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj82Brf2wM1QpoBT96gFD5ZXiJFpFTBHxKF4ghGPJwMMkkSF_ifPi4PMFM20c5ravbOTe1lhOLzrK0TDmV0Vq_wys_x09oF3VTSPh_sOrup0B5xc7CRR3tqh9zHm3DvQRIL2maSeryZ2us/s1600/bg-black-55.png);
}
.block h3 {
 font-family: 'Arial Black', Gadget, sans-serif;
 font-size: 130%;
}

The Script
jQuery(document).ready(function(){
  // saved values
  var st, 
   // get window and body elements
   win = jQuery(window)[0],
   body = jQuery('body')[0],
   wrap = jQuery('#wrapper')[0],
   // make sure we target the correct document (in IE)
   doc = (jQuery.support.boxModel) ? document.documentElement : document.body,
  
   // Set top background image height here, in pixels
   imgH = 1080;

  // vertical parallax scroll code
  jQuery(win).scroll(function(){
   // get the page scroll top (IE uses doc.scrollTop)
   st = (win.pageYOffset || doc.scrollTop );

   // Limit moving top image (in the "wrap") only when in view (st < imgH)
   // Doing this reduces the amount of DOM activity so it doesn't slow down the scrolling.
   // Here is where the background position of the top image is moved by 1/4 (st/4) of the total amount scrolled
   // Increasing the fraction (making it closer to one) will speed up the background parallax scroll
   // Decreasing the fraction will slow down the parallax scroll
   if (st < imgH) { wrap.style.backgroundPosition = 'center ' + (st/4) + 'px'; }

   // This line limits the tiled background image in the "body"
   body.style.backgroundPosition = 'left ' + ( imgH + st/4) + 'px';
  });
});
Code breakdown
  • The first and last line wrap the code which is run when the document is ready. This is a jQuery method and can be written several different ways. Basically, any code inside is run when the basic structure and code of the page has completed loading. Images may or may not have completed loading at this time.
    jQuery(document).ready(function(){
      // code to run
    });
  • The next few lines save the variables that are repeatedly used in the script. Saving them reduces the amount of time taken to run code inside the scroll function. See the optimization section for more details.
    // saved values
    var st, 
     // get window and body elements
     win = jQuery(window)[0],
     body = jQuery('body')[0],
     wrap = jQuery('#wrapper')[0],
     // make sure we target the correct document (in IE)
     doc = (jQuery.support.boxModel) ? document.documentElement : document.body,
    
    *Note that each line ends with a comma - it is defining multiple variables with one "var".

  • The next saved variable saves the top background image height (bg1.jpg). This is needed so the script can figure out where to start the tiling of the repeated background image (bgtile.jpg). This ensures that the tiled background image isn't overlapped by the top background image making the user see a sharp black edge at the overlap. The script also uses this height to stop the parallax scroll of the top background image when it isn't in view. The reason for this is discussed in the optimization section below.
    // Set top background image height here, in pixels
    imgH = 1080;
  • Now we bind to the window scroll event. This event is fired everytime the browser window is scrolled. So it can be called hundreds of times while scrolling down the page. This is the reason the code inside this function is kept as minimal as possible.
    // vertical parallax scroll code
    jQuery(win).scroll(function(){
    
      // code run each time the page is scrolled
    
    }); // second to last line in the completed script
  • Get the scroll top of the page. Check standard browsers variable, and if not defined (IE) then get the document scroll top.
    // get the page scroll top (IE uses doc.scrollTop)
    st = (win.pageYOffset || doc.scrollTop );
  • Apply the parallax to the top background image. 
    // Here is where the background position of the top image is moved by 1/4 (st/4) of the total amount scrolled
    // Increasing the fraction (making it closer to one) will speed up the background parallax scroll
    // Decreasing the fraction will slow down the parallax scroll
    if (st < imgH) { wrap.style.backgroundPosition = 'center ' + (st/4) + 'px'; }
    • The first thing we do is check if the scroll top (st) is less than the top background image height. If it is, then use parallax on the top background image.
    • "wrap" is one of our saved variables that points to the page wrapper. Here we set the background position using direct DOM manipulation. See optimization section for more details.
    • The background position has two parts - "X Y" positions. We care centering the image from left to right (the X-position), then taking one fourth (1/4) of the scroll top position and making that the background's Y-position. This is basically how the parallax scroll works. It scroll 1/4 less than the actual page. If you add another layer (say wrapper 2), it should be scrolled slightly more (a number closer to one, like 2/3).
    • So here the top background image is scrolled 1/4 less (1/4 * st) than the page itself. Make this number closer to one (i.e. 3/4 * st) to make the scroll more like the page scroll. Or make the number further from one (i.e. 1/8 * st) to make the scroll a tiny bit. Making the number too small may make the background image appear fixed, so don't go too crazy ;)
  • Apply the parallax to the tiled background image.
    // This line limits the tiled background image in the "body"
    body.style.backgroundPosition = 'left ' + ( imgH + st/4) + 'px';
    • Now we are applying the background position to the body of the page, where the tiled background image (bgtile.jpg) is seen.
    • Here we are place the background image on the left edge (centering should be fine too) and again 1/4 of the scroll top of the page. In addition we add the top image height (imgH) to keep the tiled background image aligned to the bottom of the top background image. So we make sure not to see that black image edge.
    • Since the body background image is behind the wrapper background image, you could make this parallax scroll even slower to give more of a feel of it being further off in the distance. This would look especially good with multiple background images available when using css3.
Optimizations
  • This script was optimized so that a minimal amount of code is run inside the scroll function.
  • This ensures that the code doesn't slow down the page scroll, because the scroll function is called constantly. It's probably not a big deal is modern browsers, but is very noticeable in older browsers. 
  • This was done, in part, by saving variables. This limits the amount of look ups that need to be done by the script. Using $(window) or $(document) needs to call several functions to get a value, so saving it in a variable saves time.
  • To set the background position, the script sets the background position directly in the DOM. Again, this was done to minimize function calls. I didn't have any trouble with cross browser compatibility in any browsers, including Opera and IE7+.

    Tuesday, September 28, 2010

    AnythingSlider

    I've been working on improving the AnythingSlider jQuery plugin by Chris Coyier of CSS-Tricks.com. The project was moved to github, so you can always get the latest version there... My version is up to 1.4 and you can check out a demo of it here - try starting both YouTube videos, then start the slideshow (doesn't work in Internet Explorer properly).

    Features include:
    • Panels are HTML Content (can be anything).
    • Multiple AnythingSliders allowable per-page.
    • Infinite/Continuous sliding (always slides in the direction you are going, even at "last" slide).
    • Optionally resize each panel (specified per panel in css).
    • Optional Next / Previous Panel Arrows.
    • Use keyboard navigation or tabs that are built and added dynamically (any number of panels).
    • Link to specific slides or go forward or back one slide from static text links
    • Each panel has a hashtag (can link directly to specific panels).
    • Optional custom function for formatting navigation text.
    • Auto-playing slideshow (optional feature, can start playing or stopped)
    • Pauses playing YouTube videos when not in view and resumes them when in view (only in non-IE browsers & if files are hosted on the web).
    • If slideshow is active, a playing video will complete before the slideshow continues.
    • Pauses slideshow on hover (optional).
    • Optionally play the slideshow once through, stopping on the last page.

    Sunday, July 4, 2010

    todaysImage v1.0

    The plugin will take a group of images which have a set date range, and show an image randomly from the group depending on the current date. It is based on my original Random Image by Date script but has been significantly modified and improved! It's shiny and sparkly, but you won't be able to tell much difference on the surface.

    The frame below contains a demo of this script... you can view the page directly by clicking this link so you can more easily understand what it does and test the debuging features.



    Download: Uncompressed | Minified | Zipped Demo (2.5Mb - includes all images) | Github

    Setup

    The set up is fairly simple (I hope). The page requires three things to work:
    1. jQuery loaded (you can use Google's copy as seen in the page source).
    2. An <img> anywhere on your page.
    3. Data source consisting of a date range and image url. You can also include optional comments.
    Data Format

    To include an image in this script, you will need the following bits of information:
    • Date (required) - Use the format below
    • Image URL (required)
    • Comment (optional)
    1. Date format (do not include the year):

      Dates
      Description
      0Set image as a default (will only display if no date specific images are found).
      1/1 Dispaly image only on Jan 1st.
      1/1 - 1/5Dispaly image from Jan 1st to Jan 5th (spaces are okay).
      7/20 - 8/20Display image from June 20th to August 20th.
      1/3rdMonDisplay image only on the 3rd Monday of January.
      5/lastMonDisplay image only on the last Monday of May.
      11/3rdThur-11/4thThurDisplay image from the 3rd Thursday of Nov to the 4th Thursday of Nov.
      12/20-1/1stSunDisplay image from Dec 20th to the 1st Sunday of January.

      IMPORTANT NOTES:

      • The dates that cross months (7/20-8/20) will display along with date specific images (added to the randomization).
      • Use slashes "/" to separate the month and day and dashes "-" to set a range (e.g., using "1-1 to 1-5" will break the script)
      • Using the last weekday (lastMon) of the month in the date has one restriction at this time... it'll only works for 30 day months for now. I may fix this in future versions.
      • When using the text in the date (e.g. 1st, 2nd, 3rd, last) don't spell these fully out ( first, second, third) as the script is looking for the number and not the text.
      • The weekday in the date must have at least 3 letters - these are okay: (Mon or Monday); these are not okay (M or Mo).

    2. Image URL - Umm, yeah it's required.

    3. Comment (optional)

      • The image comment will be added to the image title (or not, as desired) or into any HTML tag using an ID or class name.

      • The script is set up so that the comment can include HTML elements to add styling, but be careful to not use quotes. The script does replace quotes with the HTML escape code " but this doesn't guarantee it will work once viewed in the comment div.
    Data Sources
    • This plugin is set up to accept data from a jQuery selector (for data contained in HTML), an array or a JSON variable that is inline or retrieved remotely.
    • There is an example how to accomplish each method below and there is also a demo of each (included in the zipped file).
    • The examples below expect an image with the ID of "todaysImage"
    • All data should be presented to the script in this order: date, url, comment; you can change this order, but it will require additional option settings, described later.
    • There is no need to maintain the exact chronological order of the data. I tried to keep them this way in the demo to make finding dates easier.
    • All script should be wrapped in a $(document).ready function.
    1. HTML

      • The data can be stored in an HTML list. You point your jQuery selector at the list and tell it which attributes have the data.
      • Here is an example list (hidden using CSS):
        <ul id="myImageList">
        <li rel="0" title="images/main1.jpg">Hello</li>
        <li rel="0" title="images/main2.jpg">Hello</li>
        <li rel="12/31-1/5" title="images/new-year.jpg">Happy New Year!</li>
        <li rel="5/1-8/5" title="images/Summer.jpg">Summer time!</li>
        </ul>
        As you see, the list is stored in an <li> tag with the date in the rel attribute, the url in the title attribute and the comment inside the tag. This is how to set the script to gather the data correctly.
        $('#todaysImage').todaysImage({
        data       : $('#myImageList li'),
        dataObject : ['rel', 'title', 'html'] // these must be in this order: [date, url, comment]
        });
        The 'rel' and 'title' parts of the dataObject are attributes of the tag while the comments needs either a 'text' or 'html' to target its data; use 'html' as in the example, if you have included any styling in your comment.

        NOTE: As stated before the order of the dataObject is important - [ date, url, comment ]

    2. ARRAY

      • An array can be set up, as I did in my original script, to contain all of the data needed for this script.
      • Once again, the order these are placed in the array are important, here is a basic template:

        images.push (["DATES","IMAGE URL", "COMMENT"]);

      • Here is an example:
        var images = [];
        images.push(["0","images/main1.jpg","Hello"]);
        images.push(["0","images/main2.jpg","Hello"]);
        images.push(["12/31-1/5","images/new-year.jpg","Happy New Year!"]);
        images.push(["5/1-8/5","images/Summer.jpg","Summer time!"]);
        the script below will access this data. Notice the dataObject option sets the order of the image array. If you already have an array with similar data, all you need to do is set the dataObject to point to the correct index so that this order is maintained [ date, image URL, comments ] (e.g. images.push([ "comment", "other data", "dates", "url' ]), would required the dataObject to be [2, 3, 0]).
        $('#todaysImage').todaysImage({
        data        : images,
        dataObject  : [0,1,2]
        });
    3. JSON - inline

      • I use this method when I have a short list and want to save myself a server call.
      • Take a standard JSON object and just add "var json =" in front of it.
      • If you already have a JSON set up but it has different names (or even a different language) then just adjust the dataObject as needed
      • Here is a basic template:
        var imageList = {"images": [
        {
        "dates"  : "0",
        "image"  : "images/main1.jpg",
        "comment": "Hello"
        },{
        "dates"  : "0",
        "image"  : "images/main2.jpg",
        "comment": "Hello"
        },{
        "dates"  : "12/31-1/5",
        "image"  : "images/new-year.jpg",
        "comment": "Happy New Year!"
        },{
        "dates"  : "5/1-8/5",
        "image"  : "images/Summer.jpg",
        "comment": "Summer time!"
        }
        ]};
        The script below will access this data. Notice that "imageList" matches the variable and "images" matches the very first name in the JSON object (the key). The dataObject by default is [ 'dates', 'image', 'comment' ] which matches the JSON above; but if you have a JSON object that has different key names like "dateRange", "imageURL" and "imageComment", then you will need to set the dataObject appropriately to [ 'dataRange', 'imageURL', 'imageComment' ].
        $('#todaysImage').todaysImage({
        data: imageList.images
        });
    4. JSON - remote

      • Use this method to load JSON from your server. It won't work cross domain (unless you have it setup to work with JSONP)
      • This method requires your JSON to be valid, or the object won't parse properly (this includes removing all comments)
      • This JSON, as stated before, is essentially the same as the JSON inline.
        {"images": [
        {
        "dates"  : "0",
        "image"  : "images/main1.jpg",
        "comment": "Hello"
        },{
        "dates"  : "0",
        "image"  : "images/main2.jpg",
        "comment": "Hello"
        },{
        "dates"  : "12/31-1/5",
        "image"  : "images/new-year.jpg",
        "comment": "Happy New Year!"
        },{
        "dates"  : "5/1-8/5",
        "image"  : "images/Summer.jpg",
        "comment": "Summer time!"
        }
        ]};
        Access this remote JSON data as follows:
        $.getJSON( 'images.json', function(imageList){
        $('#todaysImage').todaysImage({
        data: imageList.images
        })
        })
        The JSON data in the example is from the file "images.json". Replace this with the URL pointing to your data. I used "imageList" as the JSON data to show the similarities to the JSON inline method. Of course "images" is the first element (key) in the JSON object, and the dataObject doesn't need modification as the names in the JSON object match.
    Customizing
    This plugin has the following default options, so you will only need to include the line below if you want to change the default:
    $('#todaysImage').todaysImage({
    data         : '', // dataObject contains the date, image and comment names as seen in the data (names if JSON, numbers [0,1,2] in an array)
    dataObject   : ['dates','image','comment'],
    comment      : '.imageComment', // class or id where the current image comment will be added; if it doesn't exist, no comment will be shown
    noImageTitle : false,           // if true, the script will not add the comment to the image's title attribute
    
    /* language options */
    dayEndings : 'st|nd|rd|th',  // 1st, 2nd, 3rd, 4th, etc. (e.g. 1stMon & 3rdThu)
    dayLast    : 'last',         // last weekday/weekend of the month
    dayWeek    : ['sun','mon','tue','wed','thu','fri','sat'], // days of the week (case insensitive)
    
    /* debugging options */
    locked          : false,// prevent debug mode onscreen output if true (debug setting from browser URL only).
    debug           : false,// set debug mode.
    debugId         : 'imagedebug', // id of the debug output div - all info and show all images will be added here.
    debugElement    : 'body',       // Location where debug id is added (where debugId div is appended)
    defaultDate     : '1/1/2010',   // date used if setting debug mode but no default date.
    inRangeColor    : '#080',       // color highlight (green) for signifying the date is in range.
    notInRangeColor : '#f00'// color highlight (red) for dates not in range.
    })
    OptionDescription
    dataPlease refer to the Data Sources section above on how to set this data
    dataObjectPlease refer to the Data Sources section above on how to set this data
    commentThis option targets the class or Id of an HTML element where you want the current image comment to be displayed, if this target doesn't exist, no comment will be shown
    noImageTitlePrevent the script from adding the comment to the image title. Done if you want to apply a tooltip to the image to display the message
    dayEndingsAbbreviation suffixes for 1st, 2nd, 3rd, 4th, etc. The script actually only uses these to match the date string, but they are ignored otherwise. So if you mistakenly add 4rd, it will use the 4 and not the "rd"
    dayLastString used to match and causes the script to find the last weekday/weekend of the month (e.g. lastMon)
    dayWeekList of days of the week. It is used to match the weekday from the data date, so this is language agnostic, but the first day of the array must start with sunday to match the javascript date method. Limit these names to three letters and the letter case doesn't matter.
    monthFirstSet to true (default) to use standard US date formatting - mm/dd/yyyy. If set to false, the European date format can be used - dd/mm/yyyy.
    lockedLocks out using the debug mode from the browser address bar (adding "#debug" to the url will enable debug mode if the script isn't locked, like my demo)
    debugEnable debug mode through the script. This value is set to true if the script is not locked and "#debug" is added to the url. This mode will display image data to show matches found and date ranges. For more detail, see the troubleshooting section below
    debugIdThis is the Id of the element to find to output the debug data. If it doesn't exist and debug mode is initiated, a div with this Id will be added to the debugElement (see below) which by default is the document body. If using the showAll() method above, this element will need to me manually added before images will be displayed.
    debugElementBy default, the debug element is the document body. This is where the debugId div is appended, if it doesn't exist, when debug mode is initiated.
    defaultDateThis date is only used if the debug mode is initiated by the script and no other date is supplied. The default date for the debug mode when adding it to the url would be the current date unless otherwise specified - see the troubleshooting section below for more details
    inRangeColorText color applied to the debug text when an image date is in range (green by default)
    notInRangeColorText color applied to the debug text when an image date is not in range (red by default)

    Methods
    You can get, set, find current number or have the script choose another random image as follows:
    • Get current image data

      • Use the "currentImage()" method to get this data.
      • This method will return an array of the currently displayed image's date, url and comment (in that order).
      • The second line was added to show how to target the image url.
      var current = $(image).data('todaysImage').currentImage(); // returns array ['dates','image url','comment']
      alert( 'current image url = ' + current[1] );
    • Set/Get current image

      • Add a number to the "currentImage()" method to set the image. An array of the image is returned (as above).
      • Setting a number that is greater than the number of images in the date range will cause the image to wrap around back to the beginning
      // Sets displayed image to the first (zero based index) image that falls within the date range,
      // then returns array ['dates','image url','comment'] of that image
      var current = $(image).data('todaysImage').currentImage(1);
    • Get current number of images

      • Use the "currentNumber()" method to get this information.
      • This value is the number of images with a date range that covered the date (e.g. if the date is 12/24, the demo script will find 8 images from which to choose)
      // return the number of images that have date ranges that match the date
      var currentNumber = $(image).data('todaysImage').currentNumber(); // returns a number
    • Random Image

      • Use the "randomImage()" method to display another random image.
      • This method will return an array of the currently displayed image's date, url and comment (in that order).
        $(image).data('todaysImage').randomImage(); // displays a random image in the date range & returns array
    • Show All Images

      • This method is used by in edit mode when clicking on the "Show All Images" button. It is useful for checking that all the image urls are correct and all the data is valid.
      // Show all images in the data, the script targets the id found in "debugId" option
      $(image).data('todaysImage').showAll();
      • This method will not work if the element targeted by the "debugId" option doesn't exist. By default, the "debugId" is "imagedebug" which is added while the script is in debug mode. But if you want to display a list somewhere else, just make sure the target exists (Id only, no class) and change the "debugId" option to match it.
        CSS
        #allImages img { height: 100px; width: 100px; } /* make images thumbnail size */
        HTML
        <div id="allImages"></div>
        Script
        // initialization of script
        $('#todaysImage').todaysImage(
        // other options here, including data source
        debugId : 'allImages'
        });
      Troubleshooting
      • If you are noticing that one image isn't showing up or something just doesn't work right, you can try to trouble shoot the problem.
      • Initiate the debug mode in the script as follows:
        // initialization of script
        $('#todaysImage').todaysImage(
        // other options here, including data source
        debug: true,
        defaultDate: '12/24/2010' // choose any date using this format
        });
      • Additionally, you can access the debug mode from the address bar simply by adding the following (in blue) to the end:

        http://myurl.com/randomImage.htm#debug:12/31/2009

        • #debug - actives the debug mode
        • 12/31/2009 - sets the date you want to check (month/day/year)

        To prevent debug from working once you are done with your script, simply set the locked variable in the script to true:
        // initialization of script
        $('#todaysImage').todaysImage(
        // other options here, including data source
        // locks out debug mode from the URL
        locked: true
        });
      • Sample debug output:
        Date used: 11/20/2009
        (11/11), derived range: 11-11 is NOT in range; image = veterans1.jpg
        (11/11), derived range: 11-11 is NOT in range; image = veterans2.jpg
        (11/11), derived range: 11-11 is NOT in range; image = veterans3.jpg
        (11/3rdThur-11/4thThur), derived range: 19-26 is in range; image = thanksgiving1.jpg
        (11/3rdThur-11/4thThur), derived range: 19-26 is in range; image = thanksgiving2.jpg
        (11/3rdThur-11/4thThur), derived range: 19-26 is in range; image = thanksgiving3.jpg
        (11/3rdThur-11/4thThur), derived range: 19-26 is in range; image = thanksgiving4.jpg

        # of currentImages = 4
        current random image = thanksgiving4.jpg
      • Try out these links to see the debug mode in action (my example script isn't locked):

        1. #debug:1.1.2010
        2. #debug:10/31/2009
        3. #debug - This will default to todays date, but edit mode is active

    Wednesday, June 30, 2010

    ImageHighlighter v1.01

    ImageHighlighter is an updated version of my original imgHighLighter plugin with lot of improvements! Most are under the hood so you probably won't see too much of a difference on the surface.

    This plugin allows you to highlight a portion of an image when you hover over a link. In the image below, the mouse is hovering over the different links and you can see the corresponding portion of the image becomes highlighted (there is an animate gif below, but just click on the image to go to the demo page).
    I set up an demo page here.

    Download: Uncompressed | Minified | Zipped Demo | Github

    I have tested this plugin in IE8, Firefox and Chrome. Please leave me feedback if you any problems with how it works or if it doesn't work in other browsers.

    7/6/2010: Updated this post to describe v1.01 where the editor portion of the script was moved into a plugin extension. And support for jCrop was added to allow selecting the entire box instead of just getting the mouse coordinates. Check out the updated demo page!

    Setup
    • This plugin requires jQuery.
    • HoverIntent is an optional plugin, this plugin will use it's functionality if it is included.
    • Follow this basic template with a quick summary for each image you want to apply imageHighlighter functionality. For more details, go to the specific section.

      HTML
      <div>
      <ul class="imgHL">
      <li>
      <a href="#" rel="sx1,sy1,ex2,ey2">Item #1</a>
      <p>Description for item #1</p>
      </li>
      <li>
      <a href="#" rel="sx1,sy1,ex2,ey2">Item #2</a>
      <p>Description for item #2</p>
      </li>
      <li>
      <a href="#" rel="sx1,sy1,ex2,ey2">Item #3</a>
      <p>Description for item #3</p>
      </li>
      </ul>
      <br>
      <img id="imgHL" src="myimage.jpg" alt="" />
      <div class="description"></div>
      </div>
      • In the HTML above, the highlight links are all wrapped in a div with a class name "imgHL" to make them easier to target.
      • The highlight links (<a>) must contain a rel attribute with the highlight box coordinates (see the Highlights section below for more detail).
      • Each link/description pair is wrapped together (inside an <li> in this case). See the Descriptions section below for more details.
      • The image is the central element. Once the script is initialized, the image will contain all of the plugin information. It is also the target of both the imageHighlighter and imageHighlighterEditor scripts.
      • The highlight description will be placed into the div with class "description". You can target a different class/Id when you modify the script options.

      CSS (basic example)
      /* List link: currently hovered/selected */
      a.current { color: #fff; }
      
      /* Hide & Position Descriptions */
      .imgHL p { display: none; }
      .description { margin: 1em auto; clear: both; width: 450px; height: 2.4em; }
      
      /* General imageHighlighter (overlay and highlight) */
      .imageHighlighter, .imgHLDark, .imgHLLight, .imgHLOverlay { padding: 0; margin: 0; } /* overlay and highlight divs */
      .imgHLOverlay { background: #000; opacity: .5; filter: alpha(opacity=50); } /* overlay color & opacity *
      • When a link is hovered and the image reveals the highlight box, the class "current" is applied to the link. You can use this to style the link and make it stand out.
      • The css definition ".imgHL p" hides the descriptions that appear under the image (in this example). The description is moved into the ".description" element when the highlight link is hovered.
      • The description class can be placed anywhere on the page; but because of this, the class name ".description" must be unique for each imageHighlighter instance on the page. You can easily modify this class name using the plugin options.
      • The general imageHighlighter definitions apply to the div wrapping the image (.imageHighlighter), the overlay (.imgHLOverlay & .imgHLDark) and the highlighted box (.imgHLLight). As you can see, the overlay has a background color and 50% opacity to darken the image behind the highlight. This can be set to transparent here in the CSS or disabled using the script.

      Javascript
      /* window load ensures all images are loaded */
      $(window).load(function(){
      $('#imgHL').imageHighlighter({
      list : '.imgHL a'
      });
      })
      • This script uses "window.load" instead of "document.ready" to ensure that all images have been loaded. This is necessary as the script needs the image dimensions in order to initialize properly.
      • In this basic example, the highlight links are targeted using the ".imgHL" div that wraps the entire list. The default list setting is "a" which is much too general to use, but the script will ignore any link that doesn't contain a rel tag.
      • There are more options that can be set. For a full list and detailed descriptions, look under the customizing/options section!

    • Highlights: The highlight link's "rel" attribute contains all the information needed for the highlights.
      rel="sx1,sy1,ex2,ey2"
      sx1Starting X position of the highlight box } top left corner
      sy1Starting Y position of the highlight box
      ex2 Ending X position of the highlight box} bottom right corner
      ey2Ending Y position of the highlight box
      You can change the highlight properties of each image using: borderColor, borderSize & borderType described in the Customizing/Options section below.

    • Image: The image must be targeted when initializing the script. You could target the class ('.imgHL') in the example above and the script will initialize once it has found the image from that group of selections. The image contains all of the data associated with this plugin, from using the built in methods to targeting custom events.
      $("#imgHL").imageHighlighter();
    • Descriptions: Each link/description pair should be wrapped together. In the demo where the links are in a paragraph, the link/description pairs are wrapped in a span:
      <span><a rel="sx1,sy1,ex2,ey2">Item #1</a><span class="desc">Description for Item #1</span></span>
      In the other example, the pair are wrapped inside of a list (<li>). Make sure that the descriptions are hidden and targeted by the "descrip" plugin option. The script will look inside the link highlight wrapper, so you don't necessarily have to have a specific class assigned to it as long as the element is unique (e.g. don't have two <p>'s inside with the highlight link otherwise the contents of both will be displayed in the description.

      The second part of the description is set using the "descripClass". The descriptions for the highlight will appear inside an element with this class, when hovering over a link. It can be located anywhere on the page, but the class/id needs to be set in the plugin options and unique for each instance of the plugin.

    • Overlay: The overlay covers the image (darkens the background) to make the highlighted portion stand out more. You can adjust the opacity of this overlay in the CSS and you can turn off the overlay functi0nality by setting the overlay option to false.
    Customizing / Options
    This plugin has the following default options, so you will only need to include the line below if you want to change the default:
    $("#imgHL").imageHighlighter({
    borderColor : "#fff",         // highlight border color
    borderSize  : 4,              // highlight border thickness
    borderType  : "solid",        // highlight border type
    list        : "a",            // links that contain the highlight coordinates (e.g. "li.imgHL a")
    descrip     : "p",            // HTML tag sibling of the link, that contains the description text (hidden) (e.g. "p.desc")
    descripClass: ".description", // HTML tag where description text is shown (placeholder)
    overlay     : true,           // display an overlay to make the highlight stand out
    current     : "current",      // class applied to link currently used to highlight the image
    hoverTimeout: 100,            // hoverIntent timeout (only applied if hoverIntent plugin is loaded)
    zindex      : 10              // z-index of highlight box, overlay is automatically made 1 less than this number
    })
    
    Methods
    You can use the following methods to get and set the highlighted content. Note that these methods must target the image.
    • Get: In the following example, the variable current will contain the current link object that has been highlighted. If nothing is currently highlighted, the script will return null.
      var $current = $('#imgHL').data('imageHighlighter').highlight();
    • Set/Get:
    • Use a number (indexed from one: first, second, etc) - if the nth link doesn't exist, it will return null.
      var $current = $('#imgHL').data('imageHighlighter').highlight(1); // select the first link
    • Search for the case-sensitive text within the link (uses the jQuery ":contains()" selector) - if the text is not found, the script will return null.
      var $current = $('#imgHL').data('imageHighlighter').highlight("frames");
    • Search for the link with a class or ID - if the selector is not found, the script will return null.
      var $current = $('#imgHL').data('imageHighlighter').highlight(".box");
    Edit Mode
    • Updated in v1.01:
      • The edit mode script was moved into an extension for the plugin. This was done because the edit script is not required once the coordinates are obtained and the script is deployed on your site.
      • Additionally, the script was made to work with the Jcrop plugin (included with the demo file zip) allowing you to use a resizable selection box to more easily get the coordinates.
      • If you click on the coordinates, the coordinates (contained in an input tag) become selected, so you can more easily copy them.

    • Edit mode for this plugin should make it easier to obtain the coordinates of the highlight box - the coordinates added to the highlight link rel attribute.

    • As of v1.01, edit mode can be activated by:

      1. Including the imageHighlighterEditor script & the jCrop plugin script, if desired.
      2. Set up the editor by calling the script on the same image(s) as the imageHighlighter script. You can generalize the call by targeting the ".imageHighlighter" class (applied to a div that wraps the image after the imageHighlighter script is applied to it). There is only one options, seen below:
        // Enable the editor and use the Jcrop plugin, if it is available
        $('div.imageHighlighter img').imageHighlighterEditor();
        
        // Enable the editor, but don't use the Jcrop plugin (even if it has been loaded)
        $('div.imageHighlighter img').imageHighlighterEditor({ useJcrop: false });
      3. Now activate or deactivate edit mode by double clicking on the image. A green bar (styled in the CSS) will appear below the image which will show the mouse coordinates (default editor) or the box coordinates (Jcrop plugin added).

    • With the editor active:

      • Default editor - move the cursor over the image to find the coordinates. Then clicking on the image will lock the coordinate display and make copying these numbers easier.
        Mouse x,y coordinates (click to lock/unlock) : x,y
      • Jcrop plugin installed - single click anywhere on the image to make the a corner of the box, then drag your mouse any direction to create a resizeable box. The coordinates of the upper left and bottom right corners of the box will display under the image:
        Current box coordinates : x1,y1,x2,y2
      • Click on the coordinates (they are inside an input tag). The contents will automatically be selected, but not copied.
      • When you hover over a highlight link, the highlight link name and coordinates from that link is displayed above the coordinate bar.
    Bugs / Suggestions
    • When the window is repositioned, the highlights may be off until it is refreshed again when you hover over a link (especially while in edit mode), and sometimes you'll need to reload the page.
    • To make suggestions or report any bugs please email me at wowmotty at g mail dot com.

    Monday, June 21, 2010

    Moving Boxes Updated

    Update (10/8/2011): A plugin is now available for WordPress for MovingBoxes v2.1.4, which you can download here or search for 'movingboxes' in your 'Install Plugins' page of your site admin section. More features and options will be added once craftyhub, the author, gets settled in :)

    Update (10/13/2010): Version 1.5 now available!

    I've updated the Moving Boxes script by Chris Coyier by converting the script into a plugin so now you can add multiple Moving Boxes blocks on the page at one time.

    I haven't done extensive testing of the script, so if you find any bugs please feel free to contact me.

    Download: uncompressed | minified | zipped file | github (see a demo!)

    Options
    • Use these key : value pairs as follows; Note that the last key : value pair does not have a trailing comma
    <script type="text/javascript">
    $(function(){
    $(selector).movingBoxes({ key: value, key: value, key: value })
    })
    </script>
    KeyValue
    (default shown)
    Description
    startPanel1Choose the initial panel to show in the scroll window.
    width800Overall width of movingBoxes.
    panelWidth.50Current panel width adjusted to 50% of movingBoxes width.
    reducedSize.8Non-current panel size: 80% of current panel size.
    imageRatio4/3Image ratio set to 4:3. Wide screen would be 16:9 (16/9).
    speed500Animation time in milliseconds for the scroll and expanding of the panel.
    hashTagstrueIf true, hash tags (browser history) are enabled.
    wrapfalseIf true,the panel will "wrap" at the ends.
    Methods
    Panels are numbered as a standard index (1st panel number is one, second is two, etc.).
    • Get number of currently selected panel:
      $('.slider').data('movingBoxes').currentPanel();
    • Set currently selected panel:
      $('.slider').data('movingBoxes').currentPanel(2);
    External controls:
    $('.slider').data('movingBoxes').goForward(); // go forward one slide (if possible)
    $('.slider').data('movingBoxes').goBack();    // go back one slide (if possible)
    

      Saturday, June 19, 2010

      Progress Indicator

      I wrote this plugin to allow more control over the progress indicator. To the right is an animated gif progress indicator. All you can do is show or hide this image. This plugin allows you to make a similar indicator that you can fully control. The plugin will animate both text (including bullets) or images, I guess you could also animate embedded objects, but I haven't tested this. The reason I call this progress indicator dynamic is you can modify or update the objects in the indicator at any time (e.g. replace images or text while the indicator is active). I'll make a demo of this when I have more time :)

      In the demo below, you can start or stop the timer to make the progression indicator simulate the animated image or you can move the slider to animate the indicator.



      Download: uncompressed | minified | zipped file | github
      (zip includes demo; go to link, then download... I'm not sure why you can't download it directly)

      Setup
      • CSS (basic setup)
        .progress {
        position: relative;
        top: 0;
        left: 0;
        width: 200px;
        height: 200px;
        overflow: hidden;
        }
        .progress span {
        position: absolute;
        left: -50px; /* hide spans until initialized */
        top: 0;
        padding: 0;
        margin: 0;
        border: 0;
        }
        .display {
        position: absolute;
        top: 95px;
        left: 90px;
        }
      • HTML
        <div class="progress">
        <!-- this displays the percent value, position in the middle with CSS -->
        <div class="display"></div>
        <!-- add as many <span>s as you want, add any text or image inside -->
        <span>&bull;</span>
        <span>&bull;</span>
        <span>&bull;</span>
        <span>&bull;</span>
        <span>&bull;</span>
        <span>&bull;</span>
        </div>
      • Script - Initialization
        <script type="text/javascript" src="jquery.progressindicator.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function(){
        // initialize: initialValue is uaually zero, and a full list of "options" can be found below.
        $(selector).progressIndicator( initialValue, options );
        })

      List of Default Settings:
      • Use these key : value pairs as follows; Note that the last key : value pair does not have a trailing comma and values that use true or false (Boolean values) should not be in quotes.
        $(selector).progressIndicator( initialValue, { key: value, key: value, key: value })
        KeyValue
        (default shown)
        Description
        max100The circle is split into this max number of increments (default set to 100 to match a percentage going from 0-99).
        radius50Sets the radius of the circle in pixels measured from the centerX and centerY position (middle).
        centerX100Positions the center of the circle 100 pixels from the left edge of its container.
        centerY100Positions the center of the circle 100 pixels from the top edge of the container.
        clockwisetrueSets the direction of the rotation. Clockwise if true and counter (or anti for you British folk) clockwise if false.
        startPosition0.75This may not make sense if you don't know the coordinate system, but basically zero is the far right side of the circle or the x-y coordinates of ( x=radius, y=0 ) . So if you want to have the indicator start with the "zero" at the top of the circle, you need to start from 75% or 3/4 of your way around the circle. So basically, set 0 to start on the right, .25 (25%) for bottom, .5 (50%) for left and .75 (75%) would be the top of the circle where ( x = 0 , y = radius ).
        sizeStart80Sets the starting size of the element to 80 pixels. This sets the font size, the height & width of any element inside the span (like an image)
        sizeDec4Sets how much to decrement the size of the next element from the starting size. Try to avoid making the decrement size that would cause the last element to be too small or negative (for example: these settings would not look good, 10 spans inside the progress indicator (in the HTML), sizeStart = 20, sizeDec = 2; this would make the last span element have a size of zero (20 - 2 * 10 = 0).
        showValuetrueAdds the progress indicator value to the "display" class inside the progress div. If you want to be tricky, add the display class to one of your spans to have the indicator move around with the other elements.
        timerActivefalseInitialize progression indicator start and stop functions allowing the indicator to move independent of the percent value.
        timerSpeed20Sets the setInterval time in milliseconds.
        timerIncrement1At each setInterval call, the progression indicator is incremented by this value. Make this number bigger to speed up the animation, but the bigger the number, the more choppy the animation.

      Methods
      • Get & Set Progression Value
        // Get current value (percentage)
        var value = $(selector).data('progressIndicator').getValue();
        
        // Set/Update current value
        $(selector).data('progressIndicator').update( value );
      • Animation timer functions (the timerActive option must be true before these will work)
        // Start animation timer
        $(selector).data('progressIndicator').start();
        
        // Stop animation timer
        $(selector).data('progressIndicator').stop();
        
        // Reset animation timer (just resets position)
        $(selector).data('progressIndicator').reset();
      Examples - Be sure to look at the demo source to see some other examples of what is possible!
      • These examples should be wrapped inside of a:

        $(document).ready(function(){ ... })

        replace the ellipsis (...) with the script in the column below.
      Action Script Notes:
      Set up timer, so the start & stop methods are available. And adjust animation speed. $('.progress').progressIndicator(
      0, {
      timerActive : true,
      showValue : false,
      timerSpeed : 20,
      timerIncrement : 1
      });

      The zero in the first line sets the initial position of the indicator, it's not really that important for the animation timer mode, but necessary to include.

      "timerActive" enables the start and stop timer methods. "showValue" is set to false to hide the progression value. "timerSpeed" and "timerIncrement" were adjusted to make the progression animation fairly quick. In the demo they are set to 50 and 5 respectively so you can see how much faster you could make this animation without it being too choppy.
      Rotate counter (anti) clockwise & other adjustments$('.progress').progressIndicator({
      clockwise : false,
      startPosition : .32,
      sizeStart : 5,
      sizeDec : -1
      });
      Setting the clockwise option to false with reverse the indicator rotation. Note that reversing the direction also effects the "startPosition" so you may need to adjust this value as well. This example is from progression3 in the demo and it needs a startPostion of .32 (32%) to move the images to the top... the reason it isn't 25% is because the sizeStart begins small (5 pixels) and the sizeDec is negative so this actually increases the image size as it progresses through the elements. You'll probably end up tweeking these numbers to get the look you want.
      Max value$('.progress').progressIndicator({
      max : 200
      });
      By default, the progress indicator is set to work with percentages.. it really only goes from 0 to 99%, but by changing the max option, you can set a full rotation of the progress indicator to any value. Note, the value, set using the update method, and the max value can be fractions.

      Saturday, September 26, 2009

      imgHighLighter - jQuery Plugin


      A newer version of this plugin is now available!

      imgHighLighter is a jQuery plugin I wrote (my first!) that allows you to highlight a portion of an image when you hover over a link. In the image below, the mouse is hovering over the "Toolbar" link and you can see the toolbar portion of the image is highlighted (click on the image to go to the demo page).
      I set up an example page here.

      This is still an early version of this plugin but I know it works with IE8, FF and Chrome. Please leave me feedback if you any problems with how it works.

      Setup
      • This plugin requires jQuery.
      • HoverIntent is an optional plugin, this plugin will use it's functionality if it is included.
      • Follow this basic template for each image you want to apply imgHighLighter functionality.

        CSS
        /* Image & descriptions */
        div.imgHL { width: 500px; margin:0 auto; }
        div.imgHL ul { text-align: center; }
        div.imgHL ul li { margin: 0; padding: 5px; list-style-type: none; float: left; }
        div.imgHL .descriptions { margin-top: 1em; clear: both; width: 450px; height: 2em; }
        div.imgHL .descriptions p {display:none;}
        
        /* General imgHighLight (overlay and highlight) */
        .imgHLOverlay { background: #000; opacity: .6; filter: alpha(opacity=60); }
        .imgHLDark, .imgHLLight, .imgHLOverlay { padding: 0; margin: 0; }
        
        /* imgHighLight Edit Mode CSS */
        .imgHLInfo { margin: 5px auto; }
        .imgHLCoords { margin: 5px auto; }
        
        HTML
        <div class="imgHL">
        <ul>
        <li><a href="#" rel="desc1:sx1,sy1,ex2,ey2">Link 1</a></li>
        <li><a href="#" rel="desc2:sx1,sy1,ex2,ey2">Link 2</a></li>
        <li><a href="#" rel="desc3:sx1,sy1,ex2,ey2">Link 3</a></li>
        </ul>
        <img class="imgHLMain" src="whole.jpg" alt="" />
        <div class="descriptions">
        <p id="desc1">Description for item #1</p>
        <p id="desc2">Description for item #2</p>
        <p id="desc3">Description for item #3</p>
        </div>
        </div>
        
        Javascript
        /* window load ensures all images are loaded */
        $(window).load(function(){
        $(".imgHL").imgHighLight();
        })
        
      • Highlights: The link's "rel" attribute contains all the information needed for the highlights.
        rel="desc1:sx1,sy1,ex2,ey2"
        desc1 = ID of the description that is associated with the highlighted area (do not include the "#")
        sx1 = Starting X position of the highlight box
        sy1 = Starting Y position of the highlight box
        ex2 = Ending X position of the highlight box
        ey2 = Ending Y position of the highlight box
        You can change the highlight properties using: borderColor, borderSize & borderType described below

      • Image: The script is set by default to find any image inside the main wrapper (.imgHL) as set by the function call
        $(".imgHL").imgHighLight();
        You can specify the exact image to modify by adding the imageID option (described below)

      • Descriptions: The wrapper class that contains the image highlight descriptions is set to "descriptions" by default. You can change this default using the descriptionWrapper option (described below). Each description within the wrapper is contained in a paragraph tag with a specific ID that matches the desc1 ID in the rel attribute.

      • Overlay: The overlay covers the image (darkens the background) to make the highlighted portion stand out more. You can adjust the opacity of this overlay in the CSS and you can turn off the overlay functi0nality (as it script does while in edit mode) by setting the overlay option.
      Customizing / Options
      This plugin has the following options:
      $(".imgHL").imgHighLight({
      borderColor: '#fff',                  // Color of the highlight border
      borderSize: '2',                      // Thickness of highlight border
      borderType: 'solid',                  // Type of highlight border
      imageID: 'img',                       // Object or ID of the main image (e.g. #myimage or just img - if it's the only img inside the container)
      descriptionWrapper: '.descriptions',  // Class wrapping all the descriptions
      overlay: true,                        // Activate overlay (default = true)
      editMode: false                       // Enable edit mode - on screen display of the image coords so you can get the info you need easier
      })
      
      Edit Mode
      • I've included an edit mode for this plugin which should make it easier for you to obtain and add the coordinates of the edges of the highlight box.

      • Edit mode can be activated in two ways:
        1. Using the editMode option when calling the plugin (described in the last section)
        2. Add a link along with the other highligh links. This method is the best as it allows you to activate and deactive edit mode.
          <li><a href="#" class="imgHLEdit">Edit Mode</a></li>
      • While in edit mode, additional information is added into the caption area... it displays the current cursor X and Y position.
        X = 0px, Y = 0px - Click to lock/unlock coordinates
      • If you click on the image while in edit mode, it locks the displayed coordinates so moving the mouse off the image won't change the display. Hopefully this will make it easier to edit your source document with the coordinates.

      • Additionally if you hover over a link, the highlight box will display (with overlay off) to allow better visualization of the highlight box.
      Bugs / Suggestions
      • At this time, the options you chose will apply to all the imgHighlighter images on the page (to be fixed in future versions)
      • When the window is repositioned, the highlights may be off until it is refreshed again when you hover over a link (especially while in edit mode), and sometimes you'll need to reload the page.
      • Future versions will allow you to highlight the image from links located anywhere on the page.
      • To make suggestions or report any bugs please email me at wowmotty at g mail dot com. Additonally, this is my first plugin, so if you can help me out with any suggestions or tips on how to improve the code I would greatly appreciate it :)

      Thursday, September 24, 2009

      Random Image by Date


      A newer version of this plugin is now available!


      The following script will show a random image depending on the date.

      The frame below contains this script... you can view it directly by clicking this link. You can view the page source from there.
      Setup

      The set up is fairly simple. The page requires two things to work:
      1. jQuery installed (you can use Google's copy as seen in the page source)
      2. An <img> anywhere on your page with an ID of "todaysimage", if it doesn't exist, it will append it to the body.
      Then you'll need to set up your image arrays as follows:
      1. In the javascript, add the template below.

        images.push (["DATES","IMAGE URL"]);

        DATES = The date range to display the image.
        IMAGE URL = Full path to your image.
      2. The DATES must follow this format:

        Dates
        Description
        0 Set image as a default (will only display if no date specific images are found).
        1/1 Dispaly image only on Jan 1st.
        1/1 - 1/5 Dispaly image from Jan 1st to Jan 5th (spaces are okay).
        7/20 - 8/20
        Display image from June 20th to August 20th.
        1/3rdMon Display image only on the 3rd Monday of Janurary.
        5/lastMon Display image only on the last Monday of May.
        11/3rdThur-11/4thThur Display image from the 3rd Thursday of Nov to the 4th Thursday of Nov.
        12/20-1/1stSun
        Display image from Dec 20th to the 1st Sunday of Janurary.

        IMPORTANT NOTES:

        • The dates that cross months (7/20-8/20) will display along with date specific images (added to the randomization).
        • Use slashes "/" to separate the month and day and dashes "-" to set a range (e.g., using 1-1 to 1-5 will break the script)
        • Using the last weekday (lastMon) of the month in the date has one restriction at this time... it'll only works for 30 day months for now. I may fix this in future versions.
        • When using the text in the date (e.g. 1st, 2nd, 3rd, last) don't spell these fully out ( first, second, third) as the script is looking for the number.
        • The weekday in the date must have at least 3 letters - these are okay: (Mon or Monday); these are not okay (M or Mo).
      Troubleshooting
      • If you are noticing that one image isn't showing up or something just doesn't work right, you can try to trouble shoot the problem.
      • Look for the following lines in the script below the "Don't change anything below this line"

        var debug = false; /* for debugging purposes */
        var thismonth = (debug) ? 11 : date.getMonth() + 1;
        var thisday = (debug) ? 20 : date.getDate();
        var thisyear = (debug) ? 2009 : date.getFullYear();

        • Set the debug variable to "true" and then adjust the date (in blue) to manually adjust the date.
        • Run the script and you can see what the script gets for results from your variables.
        • The display will show images found for the current month (thismonth variable) and show the date it derived as well as if it's within the date range.

      • Additionally, you can access the debug mode from the address bar simply by adding the following (in blue) to the end:

        http://myurl.com/randomImage.htm#debug:12/31/2009

        • #debug - actives the debug mode
        • 12/31/2009 - sets the date you want to check (month/day/year)

        To prevent debug from working once you are done with your script, simply set the locked variable in the script to true:

        /* locks out debug mode from the URL*/
        var locked = true;
      • Sample debug output:

        Date used: 11/20/2009
        (11/11), derived range: 11-11 is NOT in range; image = veterans1.jpg
        (11/11), derived range: 11-11 is NOT in range; image = veterans2.jpg
        (11/11), derived range: 11-11 is NOT in range; image = veterans3.jpg
        (11/3rdThur-11/4thThur), derived range: 19-26 is in range; image = thanksgiving1.jpg
        (11/3rdThur-11/4thThur), derived range: 19-26 is in range; image = thanksgiving2.jpg
        (11/3rdThur-11/4thThur), derived range: 19-26 is in range; image = thanksgiving3.jpg
        (11/3rdThur-11/4thThur), derived range: 19-26 is in range; image = thanksgiving4.jpg

        # of currentImages = 4
        current random image = thanksgiving4.jpg

      • Try out these links to see the debug mode in action (my example script isn't locked):

        1. #debug:1.1.2010
        2. #debug:10/31/2009
        3. #debug - This will default to todays date, but edit mode is active