Primeiros passos em jQuery

Programação Web é a Quinta-Feira

Criado por Pedro Pinto em 23 de Junho de 2011 | 9 comentários

Por Pedro Peixoto para o PPLWARE

Primeiros passos em JQuery

Nos últimos artigos temos vindo a falar da integração do Javascript nas aplicações PHP. Na última semana aumentámos um pouco mais a complexidade dos scripts, percebendo que, embora não estivéssemos a fazer nada de muito admirável, eram já necessárias algumas linhas de código. De facto o Javascript é uma linguagem completa e flexível mas pouco produtiva. Para combater este entrave surgiram bibliotecas que vieram facilitar o trabalho dos programadores. Estas bibliotecas permitem um acesso mais rápido a funcionalidades muito requeridas em aplicações WEB, para além de facilitarem o acesso à estrutura DOM e principalmente simplificarem a utilização de AJAX. Vamos por isso, aprender hoje a utilizar o JQuery.

web_01

Mas o que é o jQuery?

“jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.”

clip_image002

De facto o lema do jQuery é “Escreva menos, faça mais!”, e podemos assegurar que ambas as afirmações são verdadeiras. O Javascript foi ganhando ultimamente o seu merecido lugar de destaque, a evolução nos motores JS dos browsers, a impossibilidade do FLASH correr nos iDevices da moda, e a eminente emancipação do HTML5 muito contribuíram para isso. No entanto, existiam três pontos negativos em relação ao Javascript:

  • Em primeiro lugar é uma linguagem interpretada pelos browsers, e infelizmente nem sempre interpretada da mesma forma pelos diferentes navegadores. Nenhum programador se esquece das dores de cabeça que o já sepultado (felizmente) IE6 nos dava.
  • Outro dos problemas era o facto de o Javascript não possuir certas funcionalidades directas que a grande parte dos sites necessita. Para fazer um fadeout ou uma caixa de diálogo eram necessárias algumas linhas de código, ou até algumas funções, sendo já habito os programadores desenvolverem ficheiros .JS que permitiam funcionalidades deste tipo.
  • Por último o JS não permitia de forma fácil uma interacção imediata com as bases de dados e scripts PHP até ao aparecimento do AJAX, no entanto o AJAX também era demasiado complicado de ser usado.

Pretendia-se uma maneira fácil, rápida e bonita de programar certas funcionalidades, componentes e efeitos, para além de uniformizar a forma como os ficheiros .JS poderiam ser usados e adaptados de forma a tornarem-se autênticos PLUGINS. Surgiu então o jQuery, de facto muitos programadores WEB consideram hoje esta biblioteca uma autêntica preciosidade. Mas como “um Hello World vale mais do que mil palavras”… J … vamos ao que interessa.

Vamos como é hábito criar um ficheiro HTML com a estrutura básica já definida.

	<html>     
	<head>     	
	<title>Exemplo jQuery</title>     
	</head>          
	<body>      
	</body> 
</html>

O jQuery não é mais do que um ficheiro .JS que é necessário incluir na nossa página HTML. É possível baixar o jQuery através do próprio site:

Mas no nosso caso vamos fazer o include ficheiro directo, que está alojado no mesmo sítio:

Para incluir o ficheiro na nossa página adicionamos no head a seguinte linha de código:

http://code.jquery.com/jquery-1.6.1.min.js

E pronto estamos prontos para usar o jQuery, fácil não é? Vai ser ainda necessário uma “div” para exemplificar o funcionamento da biblioteca, e um botão para executar o código. Vamos começar por colocar o texto “Hello World!” dentro da div quando o botão Executar é clicado. Para isso basta adicionar o seguinte código ao evento click do botão:

$('#teste').html('Hello World!');

<=”” p=””>

<html>     
	<head>     	
		<title>Exemplo jQuery</title>         
		http://code.jquery.com/jquery-1.6.1.min.js     
	</head>          
	<body>     	
		
<br/> <input type="button" value="Executar" onClick="$('#teste').html('Hello World!')"> </body> </html>

E o resultado:

clip_image004

Como se pode perceber, para aceder a um elemento utilizamos a estrutura $(idouclass), com javascript simples para aceder à div teste teríamos:

Document.getElementById(‘teste’);

Com jQuery:

$(“#teste”)

O jQuery permite também aceder a elementos de uma determinada classe através do “.” em vez do “#” (como em css). Existem muitos mais selectors, podendo utilizar mesmo a navegação através da estrutura DOM à semelhança do JS mas de uma forma muito mais rápida. Aqui ficam alguns exemplos:

  • $(“p”) //aceder a todos os elementos “p”
  • $(“#pid”) //aceder ao elemento com o id “pid”
  • $(“.p”) //aceder a todos os elementos com a classe “p”
  • $(“table > tbody > tr”) //aceder a todas as linhas da tabela
  • $(“#t1 > tbody > tr”) // aceder a todas as linhas da tabela com id “#t1”
  • $(“input[type=’text’]“) // aceder aos inputs do tipo texto

Quando seleccionamos mais do que um elemento podemos usar a função each para percorrer elemento a elemento e aplicar uma acção ou então podemos usar filtros como o :first, :last e a função filter.

Em conclusão, o jQuery facilita a agiliza a programação com Javascript sendo por isso uma biblioteca indispensável. Este foi apenas um “cheirinho” para perceberem que não é de forma alguma complicado usarem esta poderosa biblioteca. Nos próximos artigos continuaremos a explorar o jQuery e também introduziremos jQuery UI de forma a aprendermos como criar aplicações/sites WEB mais atractivos e amigos do utilizador. Vamos ainda aprender a usar o jQuery em conjunto com o PHP, principalmente recorrendo ao AJAX e a funções do jQuery que tornam este recursos

Artigos relacionados

Homepage: JQuery

15 Fresh Jquery Slides

15 Fresh Jquery Slides

December 1st, 2010 in Inspiration web, Inspiration websites, Tca Inspired, web blogs by gsinspired

31

Using a jquery slide effect is getting very popular. We have choose the best one and the most complete for you. Each one of them has different options and funcionalities. Take a look at them!

 

Nivo

 

Slidesjs

 

Hevoq

 

jqfancytransitions

 

Orbit

 

Animate Panning

 

yoxview

 

quicksand

 

viewbook

 

Slide Deck

jDigiClock – Digital Clock (HTC Hero inspired).

 

jDigiClock

Digital Clock (HTC Hero inspired)

Author: Radoslav Dimov
Version: 2.1 (Changelog)
Download: jdigiclock.zip
Licence: Dual licensed under the MIT and GPL licenses.

Contents
  1. Introduction
  2. Examples
  3. Getting started
  4. Configuration
  5. Compatibility

Introduction

jDigiClock is a jQuery plugin inspired from HTC Hero Clock Widget.

Examples

Tue, 16 Mar

0°C

Update Weather …

Getting started

To use the jDigiClock plugin, include the jQuery library, the jDigiClock source file and jDigiClock core stylesheet file inside the <head> tag of your HTML document:

<link rel="stylesheet" type="text/css" href="css/jquery.jdigiclock.css" />
http://lib/jquery-1.3.2.min.js
http://lib/jquery.jdigiclock.js

To setup jDigiClock, add the following code inside the <head> tag of your HTML document:

    $(document).ready(function() {
        $('#digiclock').jdigiclock({
            // Configuration goes here
        });
    });

jDigiClock accepts a lot of configuration options, see chapter “Configuration” for further informations.

jDigiClock expects a very basic HTML markup structure inside your HTML document:

Configuration

jDigiClock accepts a list of options to control the appearance and behaviour of the Digital Clock. Here is the list of options you may set:

Property
Type
Default
Description

clockImagesPath
string
“images/clock/”
Clock images path.

weatherImagesPath
string
“images/weather/”
Weather images path.

am_pm
boolean
false
Specifies the AM/PM option.

weatherLocationCode
string
“EUR|BG|BU002|BOURGAS”
Weather location code (see: WeatherLocationDatabase.txt).

weatherMetric
string
“C”
Specifies the weather metric mode: C or F.

weatherUpdate
integer
0
Weather update in minutes.

proxyType
string
“php”
Specifies proxy type: php or asp (see: README.txt).

Compatibility

jDigiClock has been tested and works on the following browsers:

  • Internet Explorer 7 (PC)
  • FireFox 3.5 (PC/Linux)
  • Google Chrome 3.0 (PC)
  • Safari 4.0 (PC)

50 Fresh JavaScript Tools That Will Improve Your Workflow – Smashing Magazine

 

JavaScript is an integral part of the RIA revolution. JavaScript allows developers to create rich and interactive web interfaces and establish asynchronous communication with servers for constantly up-to-date data without a page refresh.

Many things that were once accomplished using Flash objects can now be built using JavaScript – with the added benefit that it is free, typically more web and mobile accessible under most circumstances using best practices for development techniques, and without the need to use proprietary software for development.

Though JavaScript has been around for a while, new tools, techniques, and information are constantly being pumped out to continually push the technology into greater heights. In this article, we wish to share with you a huge list of fresh and new tools and resources that JavaScript developers will find useful and informative.

Here are a few other posts that you might find interesting:

[By the way: The network tab (on the top of the page) is updated several times a day. It features manually selected articles from the best web design blogs!]

Useful JavaScript Tools

FireUnit
Unit testing is an integral part of building high-performance and efficient web applications. John Resig (creator of jQuery library) and Jan Odvarko have developed an excellent Firefox/Firebug extension called FireUnit which gives developers logging and testing capabilities via a simple JavaScript API. For those interested in the tool, you should also read Odvarko’s post detailing the usage of FireUnit.

Fireunit in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Sugar Test
SugarTest makes it easy to write elegant and understandable JavaScript tests. Its API is inspired by both RSpec, Shoulda and jQuery. It works as a DSL running on top of JsUnitTest.

Sugar in 50 Fresh JavaScript Tools That Will Improve Your Workflow

JS.Class: Ruby-style JavaScript
JS.Class is a library designed to facilitate object-oriented development in JavaScript. It implements Ruby’s core object, module and class system and some of its metaprogramming facilities, giving you a powerful base to build well-structured OO programs.

Ruby in 50 Fresh JavaScript Tools That Will Improve Your Workflow

JSON Formatter and Validator
The JSON Formatter was created to help with debugging. As data expressed as JSON is often written without line breaks to save space, it became extremely difficult to actually read it. This tool hopes to solve the problem by formatting the JSON into data that is easily readable by human beings.

Faux Console: Simulating a Firebug, Safari or Opera debugging in IE
Browsers like Safari, Opera and Firefox use the Firebug extension that offers a developer a comfortable way to output debugging information using the console.log() command. Microsoft Internet Explorer does not support this though – Faux Console is a small JavaScript that you can embed in the document to have a basic debugging console in IE.

JS Bin
JS Bin is a web application for testing and debugging JavaScript and CSS collaboratively. You input your source code and save it to a publicly-accessible URL which you can then share to your fellow developers or in social networking outlets like Twitter or Facebook groups. Be sure to check out the video introduction to see JS Bin in action.

Js-bin in 50 Fresh JavaScript Tools That Will Improve Your Workflow

PHP.JS
PHP.JS is an open source project in which we try to port PHP functions to JavaScript. By including the PHP.JS library in your own projects, you can use your favorite PHP functions client-side.

Page Speed
Page Speed, released by Google, is a Firefox/Firebug extension very similar to YSlow that evaluates your web pages for performance. Read more about Page Speed best practices to see what aspects of a web page are being evaluated. YSlow and Page Speed are based off Steve Souder’s work (who worked for Yahoo! and now works for Google).

Pagespeed in 50 Fresh JavaScript Tools That Will Improve Your Workflow

prettyPrint
prettyPrint is an in-browser JavaScript utility for dumping variable information, inspired by ColdFusion’s built-in cfdump utility function. Using prettyPrint on JS objects, variables, and arrays will give you a large array of information about them, which you can then use for debugging purposes or simply for gathering data about them for documentation.

Prettyprint in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Spket IDE
Spket is an excellent toolkit for JavaScript and XML development. It has a robust and intuitive GUI, and integrates with popular and powerful JavaScript/Ajax libraries such as Y!UI and jQuery. Its JavaScript Formatter feature gives you unparalleled control and standardization for you or your team’s JavaScript code formatting standards.

Spket in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Obtrusive JavaScript Checker
Obtrusive JavaScript Checker, created by Robert Nyman, is a tool for finding inline JavaScript on web pages. It highlights elements that have inline JavaScript properties and provides a summary report when you mouse over them. The tool is available as a Firefox extension or a Greasemonkey script.

Highlight.js
Highlight.js highlights syntax in code examples on blogs, forums and other web pages. The tool works automatically: it finds blocks of code, detects a language and highlights it accordingly.

High in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Javascript Compressor
Javascript Compressor is a web-based tool for compressing your JavaScript to reduce their file sizes. It works by removing unnecessary characters (such as extra tabs and spaces). Developers who use the tool to compress their code can also use the decoding feature to uncompress their source code. It also obfuscates your code, making it harder to read – which can be desirable if you want to delay prying eyes from analyzing your publicly-available code base.

Javascript-compressor in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Firediff
Firediff is a Firefox/Firebug extension that allows you to track changes in the DOM and CSS. By logging these changes, you can gain information about how web applications work, and what elements (and what properties) are being altered by way of DOM manipulation.

Firediff in 50 Fresh JavaScript Tools That Will Improve Your Workflow

RockStar Web Profiler
RockStar Web Profiler (aka Razor) logs and profiles information about client-side performance. It provides developers with a console for analyzing the data gathered by the tool. Check out the RockStar Web Profiler presentation to get an overview of its many awesome features.

bookmarklet maker
This plain and simple web tool allows you to create JavaScript-based bookmarklets. Usage is simple: simply copy and paste your source code into it and it will output the processed code in the lower pane.

Bookmarlet-maker in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Tiny JS
Tiny JS is an online directory of small but powerful plugins for popular JavaScript/Ajax libraries (MooTools, jQuery, and YUI at the moment). Its aim is to hunt down and feature lightweight plugins that give you a lot of bang for the buck.

Tiny-js in 50 Fresh JavaScript Tools That Will Improve Your Workflow

JSCharts
JS Charts is a free JavaScript based chart generator that requires little or no coding. With JS Charts drawing charts is a simple and easy task, since you only have to use client-side scripting (i.e. performed by your web browser). No additional plugins or server modules are required. It’s enough to include the scripts, prepare your chart data in XML or JavaScript Array and your chart is ready.

Glimmer
Glimmer is an interactive design tool for incorporating slick JavaScript-based animation effects using the jQuery library. Glimmer comes with a wizard-style user interface which can reduce the amount of coding that you have to write manually.

Glimmer in 50 Fresh JavaScript Tools That Will Improve Your Workflow

JSSPec
A testing environment for JavaScript that runs on IE 6+, Firefox 2+ and Safari 3+. The tool shows differences between expected value and actual value, displays the failed line exactly and supports conditional execution. Released under GNU and available for free download.

CodeRun Code Search
CodeRun’s Code Search tool lets you search and view user-submitted Ajax, PHP, and .NET source code. Once you’ve found a script or project that you’re interested in, you can edit it via their web-based IDE without having to download the project locally.

BaseJS: A Mobile (Safari) Javascript Framework
a simple, lightweight framework created specifically for Mobile Safari (perfect for iPhone development).

Coderun in 50 Fresh JavaScript Tools That Will Improve Your Workflow

MochaUI
MochaUI is a web-based tool for building web application interfaces built on top of the MooTools JavaScript framework. Jump right in by taking MochaUI for a spin in their demo page.

Mochaui in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Utility Libraries and Components for JavaScript

narwhal
narwhal is a server-side JavaScript library following the ServerJS standard. Developers can create and share “packages” for website widgets, site features, programming patterns, in a similar fashion as PEAR for PHP.

uploadify
uploadify is a useful jQuery plugin for dealing with file uploads. It’s powered by a simple PHP script for handling the server-side stuff. Be sure to check out the uploadify demos to see the plugin in action.

Blackbird
Blackbird lets you log messages in JavaScript using a simple and intuitive JS-based API. The library also provides you with an attractive console GUI for viewing and analyzing messages. No more annoying alert() functions to see your objects’ contents (which can be frustrating for printing out array values) and for setting breakpoints.

Blackbird in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Booklaylet
Booklaylet is a JS library for letting you easily deploy your bookmarklet applications. The implementation is dead simple: take the Booklaylet source and modify it to point to your app’s URL.

JavaScripTools
JavaScipTools is a collection of useful JS components, functions, and classes with the aim of addressing some of the more common web developer tasks such as parsing and formatting of data types (i.e. date and time). It also comes with a dynamic table function for creating sortable HTML tables.

Doodle.js
HTML 5’s Canvas element gives developers a way to draw stuff on web pages programmatically. Doodle.js is a utility library/framework for working with more complex and robust Canvas drawing processes. Check out Spiral Pattern demo and the Marbles in Space (3D simulation) demo in a browser that already supports Canvas to get a feel for how Doodle.js works.

Doodle-js in 50 Fresh JavaScript Tools That Will Improve Your Workflow

liteAJaX
liteAJaX is a lightweight JavaScript class for working with AJAX. This library is perfect for projects that don’t use a JavaScript/Ajax framework or projects that don’t need a more robust and fully-featured framework.

Burst
Burst is a vector animation engine for HTML 5’s Canvas element. With it, you can create smooth, Flash-like animation effects for browsers that support Canvas.

Burst in 50 Fresh JavaScript Tools That Will Improve Your Workflow

JSTestDriver
JSTestDriver is a Java-based framework for creating unit test following Test-Driven Development philosophies and best practices. Be sure to check out this video demonstration of JSTestDriver in action.

jsPDF
This library allows you to create PDF’s using nothing else but JavaScript. See the jsPDF demo page to see the library in action.

Useful JavaScript Libraries

GlassBox
GlassBox is a beautiful and refreshing take on modal windows that creates an interesting feeling of transparency as if you were looking through a glass. Check out the example page to see different types of GlassBox implementations.

Glassbox in 50 Fresh JavaScript Tools That Will Improve Your Workflow

jQuery TOOLS
jQuery TOOLS is a toolbox that gives developers some of the most popular UI design patterns at their disposal in an easy-to-use manner. View some of the things you can do with jQuery TOOLS in the project’s demo page.

Jquery-tools in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Moousture
Moosture is a JavaScript library for dealing with mouse gestures, written on top of the MooTools framework.

Tablecloth
Tablecloth is a lightweight and unobtrusive JavaScript library for styling and adding dynamic user interaction to HTML tables.

Tablecloth in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Unobtrusive Table Actions Script
This simple and lightweight library brings together a set of common and useful functions for dealing with HTML tables, such as zebra-striping rows, highlighting rows on mouse over, and column highlighting.

LivePipe
LivePipe is a set of widgets and controls for adding common user interaction components to web applications using the Prototype JavaScript framework.

Livepipe in 50 Fresh JavaScript Tools That Will Improve Your Workflow

JavaScript Graphical / Virtual Keyboard Interface
This JavaScript package adds a virtual keyboard interface into web pages.

Javascript-graphical-virtual-keyboard in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Tipmage
Tipmage is a JavaScript class for handling tooltips and annotations on images, similar to annotated images on Flickr.

Tipmage in 50 Fresh JavaScript Tools That Will Improve Your Workflow

qGallery
qGallery is a simple but beautiful JavaScript for creating image galleries with smooth and slick animation effects.

Qgallery in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Educational JavaScript Resources and Tutorials

Ajax Frameworks Decision Center
For large companies, committing to a JavaScript/Ajax framework such as Prototype, MooTools, or jQuery is a big decision because it affects a large amount of employees and will dictate the direction of the company’s client-side interaction and RIA development philosophies. Using the Ajax Frameworks Decision Center gives you an organized, quantitative, and thorough method for making a solid decision.

Ajax-decision-center in 50 Fresh JavaScript Tools That Will Improve Your Workflow

jQuery vs MooTools
This single-page site by MooTools Dev Team member Aaron Newton is a comparative look into jQuery versus MooTools.

Ajax Framework Analysis Results
This analysis of popular JavaScript/Ajax frameworks (Dojo, Ext JS, GWT, YUI) is a great resource for gathering research data for your own frameworks: the analysis matrix factors in criteria such as scalability, extensibility, quality and quantity of documentation, and much more. You can adapt this matrix, tweak their weights, and modify criterions to help you decide which JS framework to go with.

Ajax-frameworks-analysis-results in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Sexy Drop Down Menu w/ jQuery & CSS
In this tutorial, you’ll learn how to create a multi-tiered drop down menu with the use of the jQuery library.

Sexy-dropdown in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Easy Display Switch with CSS and jQuery
This tutorial outlines a method for using jQuery to smoothly-transition into different viewing modes, which can be helpful in image galleries.

Display-switch-tutorial in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Create a Slick and Accessible Slideshow Using jQuery
This is a step-by-step jQuery tutorial that I wrote for creating a simple and slick slideshow that can be adapted to display different content types. Check out the demo page to see the slideshow in action.

Accessible-jquery-slideshow in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Learning Advanced JavaScript
John Resig has a slideshow-style, web-based tutorial on advanced JavaScript development. It is a wonderful stepping-stone for JavaScript developers ready to make the leap into RIA development using JavaScript.

Learning-advanced-javascript in 50 Fresh JavaScript Tools That Will Improve Your Workflow

JavaScript tests & Compatibility tables
This resource is a well-organized cheatsheet for JavaScript methods cross-browser compatibility backed by sample tests that you can run to see how they work (or don’t work) in your browser.

Javascript-tests-compatibility-tables in 50 Fresh JavaScript Tools That Will Improve Your Workflow

Code Conventions for the JavaScript
On this page, you can find suggested coding conventions for JavaScript. It is important to note that there is no one correct convention, but this is a great place to start developing your own.

A Beautiful Apple-style Slideshow Gallery With CSS & jQuery

This week, we are making an Apple-like slideshow gallery, similar to the one they use on their website to showcase their products. It will be entirely front-end based, no PHP or databases required.

Introduction

When speaking about design, there is one company that is impossible to go without. Apple values design – being a new product, a fancy catalog or their website – there is always something to admire.

This week, we are making an Apple-like slideshow gallery, similar to the one they use on their website to showcase their products. It will be entirely front-end based, no PHP or databases required.

So go ahead and download the example source code and continue with the first step.

Step 1 – XHTML

There is no need for a database nor a PHP back-end for this gallery. This means that it is really easy to incorporate into an existing site – you just have to change a few lines of html code.

Lets take a closer look at the XHTML markup:

demo.html

<div id="main">

<div id="gallery">

<div id="slides">

<div class="slide"><img src="img/sample_slides/macbook.jpg" width="920" height="400" /></div>
<div class="slide"><img src="img/sample_slides/iphone.jpg" width="920" height="400" /></div>
<div class="slide"><img src="img/sample_slides/imac.jpg" width="920" height="400" /></div>

</div>

<div id="menu">

<ul>
<li class="fbar"> </li><li class="menuItem"><a href=""><img src="img/sample_slides/thumb_macbook.png" /></a></li><li class="menuItem"><a href=""><img src="img/sample_slides/thumb_iphone.png" /></a></li><li class="menuItem"><a href=""><img src="img/sample_slides/thumb_imac.png" /></a></li>
</ul>

</div>

</div>

</div>

The idea is simple – there are two main container DIVs – the one with id=”menu” holds the thumbnails, and the other –“slides” holds the slides themselves.

To add a new slide, you’ll just have to add new elements to both containers. The slides are JPGs, and the thumbnails are transparent PNGs, but you can use any image type you want.

You can even put any kind of HTML in as well. For example you could make a certain slide into a hyperlink by just putting the image inside of an anchor tag.

That said, it is important to have the width and height attributes set up of the slide images – it is used by jQuery to determine the width of the sliding area, as you’ll see in a moment.

Also notice that the thumbnail LI elements. The first one is assigned a class name of fbar , used to only show a vertical dividing bar, and the others are assigned a menuItem class – used as the slideshow control buttons.

Now lets continue with the next step.

Step 2 – CSS

Lets see what lays hidden in our stylesheet. I’ve only included the styles that are directly used by the gallery. You can view the rest of the styles, used to show the demo, in demo.css.

demo.css

body,h1,h2,h3,p,quote,small,form,input,ul,li,ol,label{
	/* Page reset */
	margin:0px;
	padding:0px;
}

body{
	/* Setting default text color, background and a font stack */
	color:#444444;
	font-size:13px;
	background: #f2f2f2;
	font-family:Arial, Helvetica, sans-serif;
}

/* Gallery styles */

#gallery{
	/* CSS3 Box Shadow */
	-moz-box-shadow:0 0 3px #AAAAAA;
	-webkit-box-shadow:0 0 3px #AAAAAA;
	box-shadow:0 0 3px #AAAAAA;

	/* CSS3 Rounded Corners */

	-moz-border-radius-bottomleft:4px;
	-webkit-border-bottom-left-radius:4px;
	border-bottom-left-radius:4px;

	-moz-border-radius-bottomright:4px;
	-webkit-border-bottom-right-radius:4px;
	border-bottom-right-radius:4px;

	border:1px solid white;

	background:url(img/panel.jpg) repeat-x bottom center #ffffff;

	/* The width of the gallery */
	width:920px;
	overflow:hidden;
}

#slides{
	/* This is the slide area */
	height:400px;

	/* jQuery changes the width later on to the sum of the widths of all the slides. */
	width:920px;
	overflow:hidden;
}

.slide{
	float:left;
}

#menu{
	/* This is the container for the thumbnails */
	height:45px;
}

ul{
	margin:0px;
	padding:0px;
}

li{
	/* Every thumbnail is a li element */
	width:60px;
	display:inline-block;
	list-style:none;
	height:45px;
	overflow:hidden;
}

li.inact:hover{
	/* The inactive state, highlighted on mouse over */
	background:url(img/pic_bg.png) repeat;
}

li.act,li.act:hover{
	/* The active state of the thumb */
	background:url(img/active_bg.png) no-repeat;
}

li.act a{
	cursor:default;
}

.fbar{
	/* The left-most vertical bar, next to the first thumbnail */
	width:2px;
	background:url(img/divider.png) no-repeat right;
}

li a{
	display:block;
	background:url(img/divider.png) no-repeat right;
	height:35px;
	padding-top:10px;
}

a img{
	border:none;
}

We have used a number of CSS3 specific properties in this slideshow gallery:

  • box-shadow, which makes the gallery cast a light shadow around its edges. To use it, you have to provide offsets by X and Y (0 0 here), the blurring (3px in this example) and the color of the shadow;
  • border-radius, which rounds the bottom corners of the gallery.

Unfortunately, these properties are only supported in Safari, Chrome and Firefox for now. However in the rest of the browsers you still have a completely functional gallery.

Now it is time for some jQuery magic.

Step 3 – jQuery

As I already mentioned, this gallery does not use any server-side code, so it is all up to the front end to make the slideshow tick.

script.js

$(document).ready(function(){
	/* This code is executed after the DOM has been completely loaded */

	var totWidth=0;
	var positions = new Array();

	$('#slides .slide').each(function(i){
		/* Loop through all the slides and store their accumulative widths in totWidth */
		positions[i]= totWidth;
		totWidth += $(this).width();

		/* The positions array contains each slide's commulutative offset from the left part of the container */

		if(!$(this).width())
		{
			alert("Please, fill in width & height for all your images!");
			return false;
		}
	});

	$('#slides').width(totWidth);

	/* Change the cotnainer div's width to the exact width of all the slides combined */

	$('#menu ul li a').click(function(e){

		/* On a thumbnail click */
		$('li.menuItem').removeClass('act').addClass('inact');
		$(this).parent().addClass('act');

		var pos = $(this).parent().prevAll('.menuItem').length;

		$('#slides').stop().animate({marginLeft:-positions[pos]+'px'},450);
		/* Start the sliding animation */

		e.preventDefault();
		/* Prevent the default action of the link */
	});

	$('#menu ul li.menuItem:first').addClass('act').siblings().addClass('inact');
	/* On page load, mark the first thumbnail as active */
});

The main idea behind this script is to loop through all the slides, sum up their widths and assign the sum to the slides container – the DIV with the id=”slides“. Because the slides are floated to the left and have enough room, they align next to each other.

Later, when you click a thumbnail, the script calculates which slide to show and scrolls the #slides div by assigning a negative margin via the animate method.

And with just 40 lines of code, the Apple-like slider gallery is finished!

Conclusion

In three easy steps we created a beautiful Apple-style slideshow gallery. It can be easily included into any website by just adding a few lines of code.

Fonte: A Beautiful Apple-style Slideshow Gallery With CSS & jQuery | Tutorialzine