Introduction
This is a small widget/plug-in written using HTML/CSS3 and jQuery, which results in displaying data (images or any HTML element) in a slideshow/carousel with a small amount of animation. The real purpose of this piece of code is to introduce a manner of building plug-ins/widgets (i.e., code that is usually going to be used by other people) in which the user does not have to spend as much time understanding the existing code as starting a new one from scratch.
Background
During a project I was working on, I needed to display some HTML elements in the form of a slideshow, so I thought I could get something ready to use on the internet, and then after checking several ones, I figured that the time I would spend "understanding" how to use them would be better spent on starting a new one from scratch and making sure it would be easy to integrate in future projects.
Using the Code
This is the result of what the integration code would look like:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="stylesheets/content-browser.css"
rel="stylesheet" type="text/css">
<!--
</head>
<body>
<div id="content-browser">
<!--
<img src="img1.jpg"><!--
<img src="img2.jpg"><!--
<img src="img3.jpg"><!--
<!--
</div>
<script src="js/jquery-1.8.3.min.js"></script>
<!--
<script src="js/content-browser.js"></script>
<!--
</body>
</html>
As you can see from the example above, using this widget consists of three easy steps:
- Integrating the CSS file for the Styles.
- Creating a
Div
with the ID of "content-browser
" and nesting to it as many elements as we want to display in our browser (img
tags in this example). - Invoking both the JavaScript files for jQuery and our content-browser.
The jQuery Code
Here is the code for switching between slides and their animation, nothing fancy:
$(function(){
var slide_selector = 'img';
$('#content-browser').wrap('<div id="browser-wrapper"></div>');
$('#browser-wrapper').append('<div id="cat_navigation">
<div id="centrer"></div></div>');
for(i=0;i<$('#content-browser').children().length;i++){
if(i==0){
$('#cat_navigation #centrer').append('<div class="
selected" index="'+i+'"></div>');
} else {
$('#cat_navigation #centrer').append('<div index="'+i+'"></div>');
}
}
$('#content-browser').children().css('display','none').animate({opacity:'0'});;
$('#content-browser '+slide_selector).eq(0).css('display','inherit').animate({opacity:'1'});
$('#cat_navigation #centrer div').click(function(e) {
$('#cat_navigation #centrer div.selected').removeClass("selected");
e.currentTarget.className = 'selected';
$('#content-browser').children().animate({opacity:'0'}).css('display','none');
$('#content-browser '+slide_selector).eq(e.currentTarget.getAttribute('index')).css(
'display','inherit').animate({opacity:'1'});
});
});
Points of Interest
As developers, we should always think of how the code we write would be reused later.
History