Difference between revisions of "Image slider"

From Organic Design wiki
(git links)
(use common.js)
Line 108: Line 108:
 
}
 
}
 
</source>
 
</source>
<html>
 
<script type="text/javascript">
 
// <![CDATA[
 
/**
 
* ImageSlider.js
 
*
 
* Converts div elements containing sequences of images into a sliding image display
 
* - requires jQuery
 
*
 
* Copyright (c) 2012-2015, Aran Dunkley (http://www.organicdesign.co.nz/aran)
 
*
 
* Released under the GNU General Public Licence 2.0 or later
 
*
 
*/
 
$(document).ready(function() {
 
 
"use strict";
 
 
/**
 
* Initialise all image-slider elements in the page and start them sliding
 
*/
 
$('div.image-slider').each(function() {
 
var div = $(this), i, j, w, h, img, thumb, prev, next;
 
 
// Initialise data structure in this slider element
 
div.data({
 
images: [],  // array of all the images in this slider (preloaded)
 
image:  1,  // the currently displaying image in this slider
 
last:  0,  // the previous image transitioning out
 
dir:    0,  // the direction of the current transition (-1 or +1)
 
width:  0,  // width of this sliders images
 
height: 0,  // height of this sliders images
 
});
 
 
// Set config defaults if not supplied in html data
 
if(!div.data('delay')) div.data('delay', 5);
 
if(!div.data('direction')) div.data('direction', 1);
 
if(!div.data('duration')) div.data('duration', 1000);
 
if(!div.data('thumbs')) div.data('thumbs', 0);
 
 
// Store the images in the slider element's data
 
j = $('img', div).get();
 
for( i = 0; i < j.length; i++ ) {
 
img = $(j[i]);
 
img.css('display','none');
 
div.data('images').push(img);
 
}
 
 
// Only continue initialising this slider after the first image has loaded so we can get the dimensions
 
div.data('images')[0].load(function() {
 
 
// Store the image dimentions in our slider div element's data
 
div.data('width', w = $(this).width());
 
div.data('height', h = $(this).height());
 
 
// If the slider has thumbs set then create another div with clickable thumbs in it (using the original images for the thumbs)
 
if(div.data('thumbs') > 0) {
 
thumb = $('<div class="thumbs" />');
 
for( i = 0; i < div.data('images').length; i++ ) {
 
img = div.data('images')[i];
 
img.width(div.data('thumbs'));
 
img.height(h*div.data('thumbs')/w);
 
img.css({float: 'left', cursor: 'pointer', display: ''});
 
img.data('index', i);
 
img.click(function() {
 
slide($('div.image-slider').has(this), 1, $(this).data('index'));
 
});
 
thumb.append(img);
 
}
 
}
 
 
// Restructure the content of this sliders div into layered divs with prev/next buttons and thumbs below
 
prev = '<a class="is-prev" href="javascript:">&lt; prev</a>';
 
next = '<a class="is-next" href="javascript:">next &gt;</a>';
 
div.html( '<div class="is-img1"><div class="is-img2">' + prev + next + '</div></div>' );
 
if(thumb) div.append(thumb);
 
$('.is-prev', div).click(function() { slide($('div.image-slider').has(this), -1); });
 
$('.is-next', div).click(function() { slide($('div.image-slider').has(this), 1); });
 
 
// Set the container size to the image size and other css styles
 
$('.is-img1,.is-img2',div).css({ padding: 0, width: w, height: h });
 
$('.is-prev',div).css({ float: 'left', 'margin-top': h / 2 });
 
$('.is-next',div).css({ float: 'right', 'margin-top': h / 2 });
 
 
// Start the sliding process
 
slide(div, div.data('direction'));
 
});
 
});
 
 
/**
 
* Start animating the passed div
 
* - dir is -1 or +1 for the direction to animate (left or right)
 
* - n allows the new image to be specified rather than just next/prev (it will scroll upward)
 
*/
 
function slide(div, dir, n) {
 
var nx = n === undefined,
 
    l = div.data('images').length,
 
    w = div.data('width'),
 
    h = div.data('height'),
 
    url1, url2;
 
 
// Bail if already animating, else set animation to start
 
if(div.data('dir')) return; else div.data('dir', dir);
 
 
// Set the new image either to the next according to the passed direction, or to n if passed
 
div.data('last', div.data('image'));
 
div.data('image', nx ? (div.data('image') + dir + l) % l : n);
 
url1 = div.data('images')[div.data('image')].attr('src');
 
url2 = div.data('images')[div.data('last')].attr('src');
 
 
// Show next image on regular interval
 
if(div.data('timer')) clearTimeout(div.data('timer'));
 
div.data('timer', setTimeout(function() { slide(div, div.data('direction')); }, div.data('delay') * 1000));
 
 
// Animation the last image out and the new current image in
 
div.animate({ t: 1 }, {
 
duration: div.data('duration'),
 
step: function(now, fx) {
 
var div = $(fx.elem), offset, x1, y1, x2, y2;
 
 
// Set an offset in pixels for the transition between the current and last image
 
offset = -div.data('dir') * fx.pos * (nx ? w : h);
 
 
// Calculate the positions of the current and last image (images specified with n scroll upward)
 
x1 = nx ? offset + w * dir : 0;
 
x2 = nx ? offset : 0;
 
y1 = nx ? 0 : offset + h * dir;
 
y2 = nx ? 0 : offset;
 
 
// Set the positions of the images with CSS
 
$('.is-img1', div).css( 'background', 'url("' + url1 + '") no-repeat ' + x1 + 'px ' + y1 + 'px' );
 
$('.is-img2', div).css( 'background', 'url("' + url2 + '") no-repeat ' + x2 + 'px ' + y2 + 'px' );
 
},
 
complete: function(now, fx) {
 
$(this).data('dir', 0); // mark current slider as no longer animating
 
}
 
});
 
};
 
});
 
// ]]>
 
</script>
 
</html>
 
 
[[Category:JavaScript]]
 
[[Category:JavaScript]]

Revision as of 23:38, 21 February 2016

Here's a simple image slider written 100% in JavaScript and jQuery. It converts any div elements of class "image-slider" containing img elements into a slider like the one below. You can use your own CSS rules to give the next/prev links a nicer style and make a frame around the image. The images should all be the same size for it to work properly. The code is in our Git repository here (Github here). Just copy the JavaScript into your wiki's MediaWiki:Common.js article, and any CSS rules into your wiki's MediaWiki:Common.css article.

Configuration options

There are a few configuration options which you can include in the slider element's data attributes, using the syntax shown in the usage section below. The available configuration options are as follows:

Name Default Description
thumbs 0 The pixel size of the thumbnails shown below the sliding image (0 means don't show thumbnails)
direction 1 Specifies whether the images' automatically slide to the left (-1) or right (1)
delay 5 The number of seconds delay until the image automatically slides to the next image
duration 1000 The number of milliseconds that the transition effect takes (note that this must be less than the delay)

Usage

In the wiki you can use image links as follows:

<div class="image-slider" data-thumbs="100" data-direction="-1">
    [[File:Butterfly3.jpg|512px]]
    [[File:YellowButterfly.jpg|512px]]
    [[File:MonarchOnPinkTree3.jpg|512px]]
    [[File:Butterfly1.jpg|512px]]
</div>


Here's an example of a pure HTML page which has the links to the scripts and images included:

<!DOCTYPE html>
<html lang="en">
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <head>
      <title>Image Slider</title>
      <script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
      <script src="https://code.organicdesign.co.nz/extensions/raw/master/jQuery/ImageSlider.js" type="text/javascript"></script>
   </head>
   <body>
      <div class="image-slider" data-thumbs="100">
         <img src="http://www.organicdesign.co.nz/files/thumb/1/12/Yellow_caterpillar_with_red_face.jpg/500px-Yellow_caterpillar_with_red_face.jpg" />
         <img src="http://www.organicdesign.co.nz/files/thumb/f/f2/Red_hairy_caterpillar.jpg/500px-Red_hairy_caterpillar.jpg" />
         <img src="http://www.organicdesign.co.nz/files/thumb/1/17/Green_and_red_caterpillar_2.jpg/500px-Green_and_red_caterpillar_2.jpg" />
         <img src="http://www.organicdesign.co.nz/files/thumb/1/13/Black_caterpillar_with_yellow_stripes_1.jpg/500px-Black_caterpillar_with_yellow_stripes_1.jpg" />
         <img src="http://www.organicdesign.co.nz/files/thumb/3/39/Yellow_hairy_caterpillar_2.jpg/500px-Yellow_hairy_caterpillar_2.jpg" />
      </div>
   </body>
</html>


Example

Here's a working example which has the following syntax.

<div class="image-slider" data-thumbs="100">
  [[File:Butterfly3.jpg|520px]]
  [[File:Orange and yellow butterfly 1.jpg|520px]]
  [[File:Butterfly1.jpg|520px]]
  [[File:Blue butterfly on chia.jpg|520px]]
  [[File:2015 red butterfly 2.jpg|520px]]
</div>


Butterfly3.jpg Ethilla Longwing 1.jpg Butterfly1.jpg Blue butterfly on chia.jpg 2015 red butterfly 2.jpg


CSS styles

If you want to use the same CSS as this working example, the rules are as follows. Or you can see the CSS class attributes used here to make your own rules.

/* style for next/prev links in "Image slider" page */
.image-slider .is-next, .image-slider .is-prev {
    background-color: black;
    color: white;
    text-decoration: none;
    outline: 0;
    font-size: 15px;
    font-weight: bold;
    -moz-border-radius: 11px;
    -webkit-border-radius: 11px;
    -khtml-border-radius: 11px;
    border-radius: 11px;
    padding: 5px 14px;
    margin: 5px;
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; /* IE 8 */
    filter: alpha(opacity=50);  /* IE 5-7 */
    -moz-opacity: 0.5;          /* Netscape */
    -khtml-opacity: 0.5;        /* Safari 1.x */
    opacity: 0.5;               /* Good browsers */
}
.image-slider .is-next:hover, .image-slider .is-prev:hover {
    text-decoration: none;
    outline: 0;
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
    filter: alpha(opacity=100);
    -moz-opacity: 1;
    -khtml-opacity: 1;
    opacity: 1;
}
.image-slider .thumbs {
    width: 525px !important;
}
.image-slider .thumbs img {
    margin: 5px 5px 0 0;
}