Kumpulan Artikel jQuery dan Css

Published on December 2017 | Categories: Documents | Downloads: 41 | Comments: 0 | Views: 647
of 116
Download PDF   Embed   Report

Comments

Content

Make Pretty Charts For Your App with jQuery and xCharts   

Posted on Jan 8th, 2013 AJAX jQuery PHP

DemoDownload Charts are a great visual aid when presenting data. You can’t build a professional admin panel without them. They are also tricky to set up. However, there is a new library that makes things easier – xCharts. Today, we are going to use it along with the daterange picker for Twitter Bootstrap, to build a pretty, AJAX-powered chart for your web application that fetches data from a MySQL table.

The HTML The HTML structure of the demo is pretty simple – we have to add elements on the page for the initialization of the chart, and for the date picker. As we are including bootstrap in the page anyway, we can make use of its form styling abilities and icons to make it look good.

index.php 01

<!DOCTYPE html>

02

<html>

03 04

<head> <meta charset="utf-8" />

05 06

<title>Pretty Charts with jQuery and AJAX | Tutorialzine Demo</title>

07

<link href="assets/css/xcharts.min.css" rel="stylesheet">

08

<link href="assets/css/style.css" rel="stylesheet">

09 10

<!-- Include bootstrap css -->

11

<link href="assets/css/daterangepicker.css" rel="stylesheet">

12

<link href="//cdnjs.cloudflare.com/ajax/libs/twitterbootstrap/2.2.2/css/bootstrap.min.css" rel="stylesheet" />

13 14

</head>

15

<body>

16

<div id="content">

17 18

<form class="form-horizontal">

19

<fieldset>

20

<div class="input-prepend">

21

<span class="add-on"><i class="icon-calendar"></i></span>

22

<input type="text" name="range" id="range" />

23

</div>

24

</fieldset>

25

</form>

26 27

<div id="placeholder">

28

<figure id="chart"></figure>

29

</div>

30 31

</div>

32 3 3

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js "></scr ipt>

34 35

<!-- xcharts includes -->

36

<script src="//cdnjs.cloudflare.com/ajax/libs/d3/2.10.0/d3.v2.js"></script>

37

<script src="assets/js/xcharts.min.js"></script>

38 39 40

41

<!-- The daterange picker bootstrap plugin --> <script src="assets/js/sugar.min.js"></script > <script src="assets/js/daterangepicker.js"></script>

42 43

<!-- Our main script file -->

44

<script src="assets/js/script.js"></script>

45 46 47

</body> </html>

We are including a good deal of external resources here. In the head section, we have the css files forxcharts, the datepicker, bootstrap (included from cloudflare’s super fast cdn), and our style.css file. Before the closing body tag, we have the jQuery library, d3.js (required by xcharts), xcharts, the elegant sugar.js library (required by the date range plugin), the date range plugin and our script.js. In the next steps you will see how all of these work together.

The MySQL Table As I mentioned in the intro, the script we are writing will fetch its data from a MySQL table and display it on the chart. You can find the SQL code that will create the table in schema.sql in the zip file, available for download from the buttons above. This is what the table looks like:

Database Schema It has only three fields. The date field is assigned a unique index, which means that there cannot be duplicate records for the same day. The sales_ord field holds the number of sales for the day. Your database will surely differ, but as long as you return the correct JSON response from your PHP script, there won’t be any problems (more on that in the next section). Note: Remember to enter your MySQL connection details in setup.php. You will then have to create a new MySQL database, and import schema.sql from phpMyAdmin or your management system of choice.

The PHP Code In our PHP script, we will select the records from the table that correspond to the passed start and end date, assemble an array, and output it as a JSON:

ajax.php 01

header('Content-Type: application/json');

02 03

// Set up the ORM library

04

require_once('setup.php');

05 06

if (isset($_GET['start']) AND isset($_GET['end'])) {

07 08

$start = $_GET['start'];

09

$end = $_GET['end'];

10

$data = array();

11 12

// Select the results with Idiorm

13

$results = ORM::for_table('chart_sales')

14

->where_gte('date', $start)

15

->where_lte('date', $end)

16

->order_by_desc('date')

17

->find_array();

18 19

// Build a new array with the data

20

foreach ($results as $key => $value) {

21

$data[$key]['label'] = $value['date'];

22

$data[$key]['value'] = $value['sales_order'];

23

}

24 25 26

echo json_encode($data); }

Here I am using a favorite library of mine – Idiorm. I have used it before in tutorials in the site (and in many personal projects). It is only one file (located in the lib/ folder) and makes working with databases a pure joy. All I am doing is selecting all the results from the database, which have a date value between the start and end timestamps passed with the request. The resulting JSON response looks similar to this: 01

[{

02

"label": "2013-01-07",

03

"value": "4"

04

}, {

05

"label": "2013-01-06",

06

"value": "65"

07

}, {

08

"label": "2013-01-05",

09

"value": "96"

10

}]

The label properties contain the MySQL date values for the respective row, and the values – the number of sales for that day. It is up to our JavaScript code to correctly handle this data and turn it into a format suitable for use with the xCharts plugin.

Pretty Charts with jQuery and AJAX

The JavaScript All of our JS code lies in assets/js/script.js. The code is a bit long, and to make it easier to follow I will present it to you in chunks. First we will declare a few variables and initialize the date range picker plugin. Notice that the date range I linked to is a fork of the original plugin. I decided to go with this version, as the original depends ondate.js – a very old date/time library that conflicts with xCharts. The fork instead uses sugar.js which is a nice utility library with powerful date and time support.

assets/js/script.js 01

$(function() {

02 03

// Set the default dates, uses sugarjs' methods

04

var startDate

05

endDate

= Date.create().addDays(-6), = Date.create();

06 07

var range = $('#range');

08 09

// Show the dates in the range input

// 6 days ago

// today

10

range.val(startDate.format('{MM}/{dd}/{yyyy}') + ' -

11

' + endDate.format('{MM}/{dd}/{yyyy}'));

12 13

// Load chart

14

ajaxLoadChart(startDate,endDate);

15 16

range.daterangepicker({

17 18

startDate: startDate,

19

endDate: endDate,

20 21

ranges: {

22

'Today': ['today', 'today'],

23

'Yesterday': ['yesterday', 'yesterday'],

24

'Last 7 Days': [Date.create().addDays(-6), 'today'],

25

'Last 30 Days': [Date.create().addDays(-29), 'today']

26

// You can add more entries here

27 28

} },function(start, end){

29 30

ajaxLoadChart(start, end);

31 32

});

As you can see, we are making good use of sugar.js’ date and time methods to define the start and end point of the range. I am initializing the script with the results from the last 7 days, and updating the range input field.

Now let’s create the chart: 01

// The tooltip shown over the chart

02

var tt = $('<div class="ex-tooltip">').appendTo('body'),

03

topOffset = -32;

04 05

var data = {

06

"xScale" : "time",

07

"yScale" : "linear",

08

"main" : [{

09

className : ".stats",

10

"data" : []

11 12

}] };

13 14

var opts = {

15

paddingLeft : 50,

16

paddingTop : 20,

17

paddingRight : 10,

18

axisPaddingLeft : 25,

19

tickHintX: 9, // How many ticks to show horizontally

20 21

dataFormatX : function(x) {

22 23

// This turns converts the timestamps coming from

24

// ajax.php into a proper JavaScript Date object

25 26 27

return Date.create(x); },

28 29

tickFormatX : function(x) {

30 31

// Provide formatting for the x-axis tick labels.

32

// This uses sugar's format method of the date object.

33 34 35

return x.format('{MM}/{dd}'); },

36 37

"mouseover": function (d, i) {

38

var pos = $(this).offset();

39 40

tt.text(d.x.format('{Month} {ord}') + ': ' + d.y).css({

41 42

top: topOffset + pos.top,

43

left: pos.left

44 45 46 47

}).show(); },

48

"mouseout": function (x) {

49

tt.hide();

50 51

} };

52 53

// Create a new xChart instance, passing the type

54

// of chart a data set and the options object

55 56

var chart = new xChart('line-dotted', data, '#chart' , opts);

First I define a configuration object for xCharts, with properties and callback functions. In thedataFormatX property, I am transforming the yyyy-mm-dd strings returned from the AJAX request, into proper JavaScript Date objects, so that the plugin can correctly display them and do its calculations. I am also passing an event handler for the mouseover/mouseout plugin events, and use them to show a tooltip (the plugin doesn’t come with one out of the box).

Handling Date Ranges Lastly, here is the JavaScript function for loading data with AJAX:

01 02

// Function for loading data via AJAX and showing it on the chart function ajaxLoadChart(startDate,endDate) {

03 04

// If no data is passed (the chart was cleared)

05 06

if(!startDate || !endDate){

07

chart.setData({

08

"xScale" : "time",

09

"yScale" : "linear",

10

"main" : [{

11

className : ".stats",

12

data : []

13

}]

14

});

15 16 17

return; }

18 19

// Otherwise, issue an AJAX request

20 21

$.getJSON('ajax.php', {

22 23

start: startDate.format('{yyyy}-{MM}-{dd}'),

24

end:

endDate.format('{yyyy}-{MM}-{dd}')

25 26

}, function(data) {

27 28

var set = [];

29

$.each(data, function() {

30

set.push({

31

x : this.label,

32

y : parseInt(this.value, 10)

33

});

34

});

35 36

chart.setData({

37

"xScale" : "time",

38

"yScale" : "linear",

39

"main" : [{

40

className : ".stats",

41

data : set

42

}]

43

});

44 45

});

46 47

} });

xCharts exposes the setData method so you can easily replace the displayed data. The className attribute is important, as this is what the plugin uses to identify your chart. If you omit this property, all kinds of strange bugs will occur (trust me, I know).

With this our pretty charts are complete!

We’re done! You can use this example to enhance your admin areas and to visualize statistical data in a beautiful interface.

Creating a PHP and CSS3 Powered About Page Posted on Jul 12th, 2011

 

CSS PHP

DemoDownload In this tutorial, we will be creating a simple about page that is powered by PHP, HTML5 and CSS3. It will present your contact information to your visitors, with an option for downloading it as a vCard (useful for importing it in third party applications). You can use today’s example as a placeholder for your upcoming personal website, or as an actual about page.

HTML As always, the first step is to write the HTML markup that will be powering our example. This is a simple page the main purpose of which is to present our contact details semantically. This will require adding appropriate meta tags and using the hCard microformat to embed data in the page.

index.php 01

<!DOCTYPE html>

02

<html>

03 04

05

<head> <meta charset="utf-8" /> <meta name="description" content="Online info page of <?php echo $profile>fullName()?>. Learn more about me and download a vCard." />

06 07

<title>Creating a PHP and CSS Powered About Page | Tutorialzine Demo</title>

08 09

<!-- Our CSS stylesheet file -->

10

<link rel="stylesheet" href="assets/css/styles.css" />

11 12 13

<!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js "></script>

14 15

<![endif]--> </head>

16 17

<body>

18 19

<section id="infoPage">

20

21

<img src="<?php echo $profile->photoURL()?>" alt="<?php echo $profile>fullName()?>" width="164" height="164" />

22 23

<header>

24

<h1><?php echo $profile->fullName()?></h1>

25

<h2><?php echo $profile->tags()?></h2>

26

</header>

27 28

<p class="description"><?php echo nl2br($profile->description())?></p>

29

30

<a href="<?php echo $profile->facebook()?>" class="grayButton facebook">Find me on Facebook</a>

31

<a href="<?php echo $profile->twitter()?>" class="grayButton twitter">Follow me on Twitter</a>

32 33

<ul class="vcard">

34

<li class="fn"><?php echo $profile->fullName()?></li>

35

<li class="org"><?php echo $profile->company()?></li>

36

<li class="tel"><?php echo $profile>cellphone()?></li>

37

<li><a class="url" href="<?php echo $profile->website()?>"><?php echo $profile->website()?></a></li>

38

</ul>

39 40

</section>

41 42

<section id="links">

43

<a href="?vcard" class="vcard">Download as V-Card</a>

44

<a href="?json" class="json">Get as a JSON feed</a>

45

46

<p>In this tutorial: <ahref="http://www.flickr.com/photos/levycarneiro/4144428707/ ">Self Portrait</a> by <ahref="http://www.flickr.com/photos/levycarneiro/ ">Levy Carneiro Jr</a></p> </section>

47 48 49

</body> </html>

The $profile variable you see above, holds an object of the AboutPage PHP class that we will be writing in a moment. It holds our contact details and provides a number of useful methods for generating JSON and vCard files. As mentioned above, we are using the hCard microformat to embed contact details in the page. This is a simple standard with which we use the class names of regular HTML elements to specify data, easily recognizable by search engines. The hCard holds information about our full name, organization, phone and home page: 1

<ul class="vcard">

2

<li class="fn"><?php echo $profile->fullName()?></li>

3

<li class="org"><?php echo $profile->company()?></li>

4

<li class="tel"><?php echo $profile>cellphone()?></li>

5

<li><a class="url" href="<?php echo $profile->website()?>"><?php echo $profile>website()?></a></li>

6

</ul>

You can also optionally specify a home / work address and other kinds of useful information.

PHP & CSS3 Powered About Page

PHP One of the points of using a server side language is that we can leave some aspects of the page to be generated on the fly. This frees us from having to manually keep various parts of the page up to date. In the case with our about page, we have a simple configuration file, which holds the data, used by the page. This same resource is used for the generation of the vCard file and the JSON feed.

config.php 01

$info = array(

02

'firstName'

03

'middleName'

04

'lastName'

=> 'John', => 'S.', => 'Smith',

05

'photoURL'

06

'birthDay'

07

'city'

08

'country'

09

'street'

10

'zip'

11

'company'

12

'website'

13

'email'

14

'cellphone'

=> '12345678910',

15

'description'

=> "I am a webdeveloper living in ...",

16

'tags'

17

18

19

'facebook'

=> 'assets/img/photo.jpg', => strtotime('22-03-1983'), => 'MyCity', => 'United States', => 'My Street 21', => '12345', => 'Google Inc', => 'http://tutorialzine.com/', => '[email protected]',

=> 'Developer, Designer, Photographer', => 'http://www.facebook.com/'

, 'twitter'

=> 'http://twitter.com/Tutorialzine

' );

Not all of these properties are presented on the about page. Some of them (like the address fields,company, email and birthday) are only made available when the user downloads the profile as a vCard or as a JSON file. You can also add quite a few more properties to this array (a complete list is given as a comment in the config.php file). So now that we have provided all the information we wanted, we need to build a class that will handle the task of presenting a complete about page.

aboutPage.class.php 001 002

class AboutPage{ private $info = array();

003 004

// The constructor:

005 006

public function __construct(array $info){

007 008

$this->info = $info; }

009 010

// A helper method that assembles the person's full name:

011 012

public function fullName(){

013 014

return $this->firstName().' '.$this->middleName().' '.$this->lastName(); }

015 016

// Using PHP's Magick __call method to make the

017

// properties of $this->info available as method calls:

018 019

public function __call($method,$args = array()){

020 021

if(!array_key_exists($method,$this->info)){

022 023

throw new Exception('Such a method does not exist!'); }

024 025

if(!empty($args)){

026

$this->info[$method] = $args[0];

027

}

028

else{

029

return $this->info[$method];

030 031

} }

032 033

// This method generates a vcard from the $info

034

// array, using the third party vCard class:

035 036

public function downloadVcard(){

037 038

$vcard = new vCard;

039 040

$methodCalls = array();

041 042

// Translating the properties of $info to method calls

043

// understandable by the third party vCard class:

044 045

$propertyMap = array(

046

'firstName'

047

'middleName'

048

'lastName'

049

'birthDay'

050

'city'

=> 'setHomeCity',

051

'zip'

=> 'setHomeZIP',

052

'country'

=> 'setFirstName', => 'setMiddleName', => 'setLastName', => 'setBirthday',

=> 'setHomeCountry',

053

'website'

054

'email'

055

'description'

=> 'setNote',

056

'cellphone'

=> 'setCellphone');

=> 'setURLWork', => 'setEMail',

057 058

// Looping though the properties in $info:

059 060

foreach($this->info as $k=>$v){

061 062

// Mapping a property of the array to a recognized method:

063 064

if($propertyMap[$k]){

065

$methodCalls[$propertyMap[$k]] = $v;

066

}

067

else {

068 069

// If it does not exist, transform it to setPropertyName,

070

// which might be recognized by the vCard class:

071 072

$methodCalls['set'.ucfirst($k)] = $v;

073 074

} }

075 076

// Attempt to call these methods:

077 078

foreach($methodCalls as $k=>$v){

079

if(method_exists($vcard,$k)){

080

$vcard->$k($v);

081

}

082

else error_log('Invalid property in your $info array: '.$k);

083

}

084 085

// Serving the vcard with a x-vcard Mime type:

086 087

header('Content-Type: text/x-vcard; charset=utf-8');

088

header('Content-Disposition: attachment; filename="'.$this->fullName().'.vcf"');

089

echo $vcard->generateCardOutput();

090

}

091 092

// This method generates and serves a JSON object from the data:

093 094

public function generateJSON(){

095

header('Content-Type: application/json');

096

header('Content-Disposition: attachment; filename="'.$this->fullName().'.json"');

097 098

099

// If you wish to allow cross-domain AJAX requests, uncomment the following line: // header('Access-Control-Allow-Origin: *');

100 101

echo json_encode($this->info);

102

}

103

}

As you can see from the code below, we are using a third party open source class for the actual generation of the vCard file (vcf). As this class uses its own set of method calls, we will need to transform our configuration file to something that it will understand. We are doing this with the $propertyMap array which maps properties found in our $info array to the names of method calls that will need to be executed on the vCard object. After we configure the $vcard object, we set the content headers and call the object’s generateCardOutput() method. This causes the browser to display a file download dialog. We are doing basically the same thing in the generateJSON method, with the worthy exception that we are not using a third party PHP class, but the json_encode() built-in. We are serving the JSON file with an application/json content type. You can also uncomment the access control header if you wish to be able to access your data via AJAX from other domains. Now lets see how we are using this class in index.php:

index.php 01

require 'includes/config.php';

02

require 'includes/aboutPage.class.php';

03

require 'includes/vcard.class.php';

04 05

$profile = new AboutPage($info);

06 07

if(array_key_exists('json',$_GET)){

08

$profile->generateJSON();

09

exit;

10

}

11

else if(array_key_exists('vcard',$_GET)){

12

$profile->downloadVcard();

13

exit;

14

}

The fragment you see above is found at the top of index.php, before any of the HTML, as we have to be able to set headers. After including the appropriate PHP source files, we create a new AboutPage object with the configuration array as its parameter. After this we check whether the requested URL is ?json or ?vcard, and serve the appropriate data. Otherwise, the regular about page is displayed.

CSS Most of the design of the about page is pretty straightforward. However, a fair share of CSS3 is used to keep the number of images to a minimum. The two buttons – Find me on facebook, and Follow me on twitter, that are positioned below the text, are ordinary hyperlinks with a .grayButton class name. You can see the definition of this class below:

assets/css/styles.css 01

a.grayButton{

02

padding:6px 12px 6px 30px;

03

position:relative;

04 05

background-color:#fcfcfc;

06

background:-moz-linear-gradient(left top -90deg, #fff, #ccc);

07

background:-webkit-linear-gradient(left top -90deg, #fff, #ccc);

08

background:linear-gradient(left top -90deg, #fff, #ccc);

09 10

-moz-box-shadow: 1px 1px 1px #333;

11

-webkit-box-shadow: 1px 1px 1px #333;

12

box-shadow: 1px 1px 1px #333;

13 14

-moz-border-radius:18px;

15

-webkit-border-radius:18px;

16

border-radius:18px;

17 18

font-size:11px;

19

color:#444;

20

text-shadow:1px 1px 0 #fff;

21

display:inline-block;

22

margin-right:10px;

23 24

-moz-transition:0.25s;

25

-webkit-transition:0.25s;

26

transition:0.25s;

27

}

28 29

a.grayButton:hover{

30

text-decoration:none !important;

31

box-shadow:0 0 5px #2b99ff;

32

}

33 34

a.grayButton:before{

35

background:url('../img/icons.png') no-repeat;

36

height: 18px;

37

left: 4px;

38

position: absolute;

39

top: 6px;

40

width: 20px;

41

content: '';

42

}

43 44

a.grayButton.twitter:before{

45 46

background-position:0 -20px; }

The code above applies a CSS3 linear gradient to the button, text shadows and rounded corners. It also defines a 0.25 sec transition, that animates the glow that is applied on hover. We are also using the:before pseudo element to create the icon that goes with the button. As we are using a sprite, the only thing that differs between the two buttons is the offset of the background image. After this we have the “Download as vCard” and “Get as a JSON file” links:

assets/css/styles.css 01

#links{

02

text-align:center;

03

padding-top: 20px;

04

border-top:1px solid #4a4a4a;

05

text-shadow: 1px 1px 0 #333333;

06

width:655px;

07

margin:0 auto;

08

}

09 10

#links a{

11

color: #ccc;

12

position:relative;

13

}

14 15

#links > a{

16

display: inline-block;

17

font-

size: 11px; 18

margin: 0 10px;

19

padding-left:15px;

20

}

21 22

#links > a:before{

23

background: url("../img/icons.png") no-repeat -10px -60px;

24

position:absolute;

25

content:'';

26

width:16px;

27

height:16px;

28

top:2px;

29

left:-4px;

30

}

31 32

#links > a.vcard:before{

33

background-position: -10px -40px;

34

top: 0;

35

left: -8px;

36

}

37 38 39 40

#links p{ color: #888888; fontsize: 10px;

41

font-style: normal;

42

padding: 30px;

43

}

As the #links section element contains more than these links (it contains a paragraph with a link to a great portrait image by Levy Carneiro Jr.) , we have to limit the styling to the anchor elements that are direct children of the section. With this our PHP & CSS3 powered about page is complete!

To Wrap it up You can use this about page as a simple placeholder for your personal website. You can also use an existing users database and create beautiful profiles for your users. Combined with some of our previous tutorials, you can display your latest posts on facebook, flickr images or tweets as a personalized home page.

Creating a Stylish Coming Soon Page with jQuery Posted on Oct 27th, 2010

  

CSS jQuery PHP

DemoDownload When starting work on a new website idea, the first thing you probably do is to acquire the domain name and set up some sort of a coming soon page (remember those construction site gif animations? Don’t use them!). It is actually a good idea to invest some time in the development of this page. This is the first encounter visitors have with you and your product. You can even use it as a marketing channel and let people subscribe to your launch newsletter. This is why, today we are creating a stylish coming soon page, using PHP, MySQL and jQuery. It will allow you to collect visitors’ emails and store them in a simple database table. On the presentation side, it features a slick slideshow with the help of the Nivo Slider plugin.

The HTML First lets take a look at the HTML markup of the coming soon page. The page was designed to be lightweight and has only a minimal amount of code.

coming-soon.php 01

<!DOCTYPE html>

02

<html>

03

<head>

04

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

05

<title>AJAX-ed Coming Soon Page with jQuery and PHP | Tutorialzine Demo</title>

06 07

<link rel="stylesheet" type="text/css" href="css/styles.css" />

08

<link rel="stylesheet" type="text/css" href="css/nivo-slider.css" />

09 10

</head>

11 12

<body>

13 14

<div id="page">

15 16

<h1>Coming Soon</h1>

17 18 19

<div id="slideshowContainer"> <div id="slideshow">

20

<img src="img/slides/slide1.jpg" width="454" height="169" alt="Coming Soon: Our Awesome Web App">

21

<img src="img/slides/slide2.jpg" width="454" height="169" alt="Extensive Functionality">

22

<img src="img/slides/slide3.jpg" width="454" height="169" alt="Complete with an iPhone App">

23 24

</div> </div>

25 26

<h2>Subscribe</h2>

27 28

<form method="post" action="">

29

<input type="text" id="email" name="email" value="<?php echo $msg?>" />

30

<input type="submit" value="Submit" id="submitButton" />

31

</form>

32 33 34

</div>

35

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js "></script>

36

<script src="js/jquery.nivo.slider.pack.js"></script>

37

<script src="js/script.js"></script>

38 39

</body>

40

</html>

In the head section, we include the stylesheets – our own styles.css and nivo-slider.css, used by the Nivo Slider plugin. You can potentially merge these two files into one to requests, but it would be an overkill in this case. In the body section, we define the main markup – basically two headings, a form, and a div container with three images, used by the slider. At the bottom we include three JavaScript files. The first one imports jQuery 1.4.3 from Google’s CDN, which is the newest version of the library at the moment of this writing. After it comes the nivo slider js include file, and lastly our own script.js, which is discussed in detail in the last section of this tutorial.

AJAX-ed Coming Soon Page with jQuery, PHP and MySQL

The CSS

The CSS styles, which affect the page, are defined in styles.css. To make it easier to modify and include into an existing design, some of the rules are prefixed with the #page selector, which limits the effect of the rules only to the specified elements – CSS namespacing.

css/styles.css 01

#page{

02

width:330px;

03

margin:70px auto 100px;

04

}

05 06

#slideshow{

07

height:169px;

08

overflow:hidden;

09

width:454px;

10

}

11 12

#slideshowContainer{

13

padding:10px;

14

background-color:#181819;

15

margin:30px 0 50px -72px;

16

width:454px;

17

border:1px solid #1f1f20;

18

}

19 20

#page h1,

21

#page h2{

22

text-indent:-9999px;

23

overflow:hidden;

24

height:105px;

25

background:url('../img/coming_soon.png') no-repeat;

26

}

27 28

#page h2{

29

height:76px;

30

background:url('../img/get_notified.png') no-repeat;

31

margin-bottom:20px;

32

}

33 34

#page form{

35

background-color:#181819;

36

display:block;

37

height:31px;

38

padding:10px;

39

position:relative;

40

width:323px;

41

margin-left:-7px;

42 43

-moz-border-radius:3px;

44

-webkit-border-radius:3px;

45

border-radius:3px;

46

}

47 48

#email{

49

background:url('../img/submit_form.png') no-repeat;

50

border:none;

51

color:#888888;

52

height:31px;

53

left:10px;

54

line-height:31px;

55

padding-left:8px;

56

position:absolute;

57

text-shadow:1px 1px 0 #FFFFFF;

58

top:10px;

59

width:215px ;

60 61

outline:none; }

62 63

#submitButton{

64

background:url('../img/submit_form.png') no-repeat right top;

65

border:none;

66

cursor:pointer;

67

height:31px;

68

left:236px;

69

line-height:31px;

70

position:absolute;

71

text-indent:-99999px;

72

text-transform:uppercase;

73

top:10px;

74

width:96px;

75

}

76 77

#submitButton:hover{

78 79

background-position:right bottom; }

Things are pretty much clear here. Something that is worth noting, is probably the negative textindenttechnique, which is used extensively to display a background image and hide the contents of the element. A gotcha of this method, when applied to submit buttons, is that you need to force the text into uppercase with text-transform, otherwise it would not work in older versions of IE.

Email Subscribe Form

The PHP To make this page as simple as possible, the PHP code that handles the form submission, is located at the top of the document. This also makes it easier to handle situations in which JavaScript is not available, and the form is submitted in the normal way (notice that in the HTML step the action attribute of the form is empty – it will be submitted to the same page).

coming-soon.php 01 02

require "includes/connect.php";

03

$msg = '';

04 05

if($_POST['email']){

06 07

// Requested with AJAX:

08

$ajax = ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');

09 10 11

try{ if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){

12 13

throw new Exception('Invalid Email!'); }

14 15

$mysqli->query("INSERT INTO coming_soon_emails

16

SET email='".$mysqli->real_escape_string($_POST['email'])."'");

17 18

if($mysqli->affected_rows != 1){

19 20

throw new Exception('This email already exists in the database.'); }

21 22

if($ajax){

23 24

die('{"status":1}'); }

25 26

$msg = "Thank you!";

27 28

}

29

catch (Exception $e){

30 31

if($ajax){

32

die(json_encode(array('error'=>$e->getMessage())));

33

}

34 35

$msg = $e->getMessage();

36 37

} }

If the form was submitted via AJAX (we can tell if this is so by checking for the X_REQUESTED_WITHheader) we output the responses as JSON, otherwise we assign them to the $msg variable that is later printed to the page. As we are using the MySQLi extension, after we insert the email in the coming_soon_emails table (it contains only an email column and a timestamp) we need to check the affected rows property. The email column is defined as a primary key, and the insert will fail on a duplicate email address. Installation Notes: if you want to set up the Coming Soon Page on your host, you will need to create the coming_soon_emails table by running table.sql (available in the zip download) in phpMyAdmin. After this, remember to add your MySQL connection details to includes/connect.php.

The jQuery As we are using the Nivo Slider plugin, a lot of the work has been done for us, and we can move our attention to handling the form submission and AJAX responses.

js/script.js 01

$(window).load(function() {

02 03

// Creating the Nivo Slider on window load

04 05 06

$('#slideshow').nivoSlider({ pauseTime:5000,

07

directionNav:false,

08

controlNav:false

09 10

}); });

11 12

$(document).ready(function(){

13 14

// Binding event listeners for the form on document ready

15 16

$('#email').defaultText('Your Email');

17 18

// 'working' prevents multiple submissions

19

var working = false;

20 21

$('#page form').submit(function(){

22 23

if(working){

24

return false;

25

}

26

working = true;

27 28 29 30

$.post("./coming-soon.php",{email:$('#email').val()},function(r){ if(r.error){ $('#email').val(r.error);

31

}

32

else $('#email').val('Thank you!');

33 34

working = false;

35

},'json');

36 37

return false;

38 39

}); });

40 41

// A custom jQuery method for placeholder text:

42 43

$.fn.defaultText = function(value){

44 45

var element = this.eq(0);

46

element.data('defaultText',value);

47 48 49

element.focus(function(){ if(element.val() == value){

50 51 52 53 54

element.val('').removeClass('defaultText'); } }).blur(function(){ if(element.val() == '' || element.val() == value){ element.addClass('defaultText').val(value);

55

}

56

});

57 58 59

return element.blur(); }

Notice that the Nivo Slider slideshow is created on the window.load event. This is done, so that we can be sure that all the images are loaded and can be displayed. Although this is the first code block on the page, it is actually executed last. In the document. ready block, we bind an event listener for the form’s submit event. As the handler returns a boolean false value, the form will not get submitted, instead we are sending an AJAX post request back to the same page and get either a successful response, or an error, which gets outputted as the value of the email input box. With this our Stylish AJAX-ed Coming Soon Page is complete!

Wrapping it up You can use this page to introduce early visitor to the features of your upcoming website. You can extend it with an arbitrary amount of slides, and maybe improve its SEO by adding a paragraph or two about each slide. The biggest benefit by far is giving an option for email subscriptions. You can later just pop into phpMyAdmin and export a friendly CSV file, ready for import in your favorite email marketing application.

Making a Beautiful HTML5 Portfolio Posted on Jun 17th, 2011

 

CSS jQuery

DemoDownload In today’s tutorial we will be making a beautiful HTML5 portfolio powered by jQuery and the Quicksand plugin. You can use it to showcase your latest work and it is fully customizable, so potentially you could expand it to do much more.

The HTML The first step is to write down the markup of a new HTML5 document. In the head section, we will include the stylesheet for the page. The jQuery library, the Quicksand plugin and our script.js will go right before the closing body tag:

index.html 01

<!DOCTYPE html>

02

<html>

03 04

<head> <meta charset="utf-8" />

05 06

<title>Making a Beautiful HTML5 Portfolio | Tutorialzine Demo</title>

07 08

<!-- Our CSS stylesheet file -->

09

<link rel="stylesheet" href="assets/css/styles.css" />

10 11

<!-- Enabling HTML5 tags for older IE browsers -->

12

<!--[if lt IE 9]>

13 14 15

<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js "></script> <![endif]--> </head>

16 17

<body>

18 19

<header>

20

<h1>My Portfolio</h1>

21

</header>

22 23

<nav id="filter">

24

<!-- The menu items will go here (generated by jQuery) -->

25

</nav>

26 27

<section id="container">

28

<ul id="stage">

29

<!-- Your portfolio items go here -->

30

</ul>

31

</section>

32 33

<footer>

34

</footer>

35 36

<!-- Including jQuery, the Quicksand plugin, and our own script.js -->

37 3 8

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js "></scri pt>

39

<script src="assets/js/jquery.quicksand.js"></script>

40

<script src="assets/js/script.js"></script>

41 42 43

</body> </html>

In the body, there are a number of the new HTML5 elements. The header holds our h1 heading (which is styled as the logo), the section element holds the unordered list with the portfolio items (more lists are added by jQuery, as you will see later), and the nav element, styled as a green bar, acts as a content filter. The #stage unordered list holds our portfolio items. You can see what these items should look like below. Each of them has a HTML5 data attribute, which defines a series of comma-separated tags. Later, when we use jQuery to loop through this list, we will record the tags and create categories that can be selected from the green bar. 01 02 03

<li data-tags="Print Design"> <img src="assets/img/shots/1.jpg" /> </li>

04 05

<li data-tags="Logo Design,Print Design">

06

<img src="assets/img/shots/2.jpg" />

07

</li>

08 09

<li data-tags="Web Design,Logo Design">

10

<img src="assets/img/shots/3.jpg" />

11

</li>

You can put whatever you want in these li items and customize the portfolio further. The Quicksand plugin will handle the animated transitions of this list, so you are free to experiment.

Beautiful HTML5 Portfolio with jQuery

The jQuery What the Quicksand plugin does, is compare two unordered lists of items, find the matching LIs inside them, and animate them to their new positions. The jQuery script we will be writing in this section, will loop through the portfolio items in the #stage list, and create a new (hidden) unordered list for each of the tags it finds. It will also create a new menu option, which will trigger the quicksand transition between the two lists. First we need to listen for the ready event (the earliest point in the loading of the page where we can access the DOM), and loop through all the li items detecting the associated tags.

script.js – Part 1 01

$(document).ready(function(){

02 03 04

var items = $('#stage li'), itemsByTags = {};

05 06

// Looping though all the li items:

07 08

items.each(function(i){

09

var elem = $(this),

10

tags = elem.data('tags').split(',');

11 12

// Adding a data-id attribute. Required by the Quicksand plugin:

13

elem.attr('data-id',i);

14 15

$.each(tags,function(key,value){

16 17

// Removing extra whitespace:

18

value = $.trim(value);

19 20

if(!(value in itemsByTags)){

21

// Create an empty array to hold this item:

22

itemsByTags[value] = [];

23

}

24 25

// Each item is added to one array per tag:

26

itemsByTags[value].push(elem);

27

});

28 29

});

Each tag is added to the itemsByTags object as an array. This would mean that itemsByTags['Web Design'] would hold an array with all the items that have Web Design as one of their tags. We will use this object to create hidden unordered lists on the page for quicksand.

It would be best to create a helper function that will handle it for us:

script.js – Part 2 01

function createList(text,items){

02 03

// This is a helper function that takes the

04

// text of a menu button and array of li items

05 06

// Creating an empty unordered list:

07

var ul = $('<ul>',{'class':'hidden'});

08 09

$.each(items,function(){

10

// Creating a copy of each li item

11

// and adding it to the list:

12 13 14

$(this).clone().appendTo(ul); });

15 16

ul.appendTo('#container');

17 18

// Creating a menu item. The unordered list is added

19

// as a data parameter (available via .data('list')):

20 21

var a = $('<a>',{

22

html: text,

23

href:'#',

24

data: {list:ul}

25 26

}).appendTo('#filter'); }

This function takes the name of the group and an array with LI items as parameters. It then clones these items into a new UL and adds a link in the green bar. Now we have to loop through all the groups and call the above function, and also listen for clicks on the menu items.

script.js – Part 3 01

// Creating the "Everything" option in the menu:

02

createList('Everything',items);

03 04

// Looping though the arrays in itemsByTags:

05

$.each(itemsByTags,function(k,v){

06 07

createList(k,v); });

08 09 10

$('#filter a').live('click',function(e){ var link = $(this);

11 12

link.addClass('active').siblings().removeClass('active');

13 14

// Using the Quicksand plugin to animate the li items.

15

// It uses data('list') defined by our createList function:

16 17

$('#stage').quicksand(link.data('list').find('li'));

18

e.preventDefault();

19

});

20 21

// Selecting the first menu item by default:

22

$('#filter a:first').click();

Great! Now that we have everything in place we can move on to styling the page.

The CSS

Styling the page itself is not that interesting (you can see the CSS for this in assets/css/styles.css). However what is more interesting is the green bar (or the #filter bar), which uses the :before / :after pseudo elements to add attractive corners on the sides of the bar. As these are positioned absolutely, they also grow together with the bar.

styles.css 01

#filter {

02

background: url("../img/bar.png") repeat-x 0 -94px;

03

display: block;

04

height: 39px;

05

margin: 55px auto;

06

position: relative;

07

width: 600px;

08

text-align:center;

09 10

-moz-box-shadow:0 4px 4px #000;

11

-webkit-box-shadow:0 4px 4px #000;

12

box-shadow:0 4px 4px #000;

13

}

14 15 16

#filter:before, #filter:after { background: url("../img/bar.png") no-repeat;

17

height: 43px;

18

position: absolute;

19

top: 0;

20

width: 78px;

21

content: '';

22 23

-moz-box-shadow:0 2px 0 rgba(0,0,0,0.4);

24

-webkit-box-shadow:0 2px 0 rgba(0,0,0,0.4);

25

box-shadow:0 2px 0 rgba(0,0,0,0.4);

26

}

27 28

#filter:before {

29

background-position: 0 -47px;

30

left: -78px;

31

}

32 33

#filter:after {

34

background-position: 0 0;

35

right: -78px;

36

}

37 38

#filter a{

39

color: #FFFFFF;

40

display: inline-block;

41

height: 39px;

42

line-height: 37px;

43

padding: 0 15px;

44

text-shadow:1px 1px 1px #315218;

45

}

46 47

#filter a:hover{

48 49

text-decoration:none; }

50 51

#filter a.active{

52

background: url("../img/bar.png") repeat-x 0 -138px;

53

box-shadow: 1px 0 0 rgba(255, 255, 255, 0.2),

54

-1px 0 0 rgba(255, 255, 255, 0.2),

55

1px 0 1px rgba(0,0,0,0.2) inset,

56

-1px 0 1px rgba(0,0,0,0.2) inset;

57

}

Before / After Elements With this our beautiful HTML5 portfolio is complete!

Conclusion You can use this template to present your work. The best thing about it is that it’s really easy to customize. You only need to change the contents of the initial LI items of the #stage list, and specify some new tags – the script will do the rest. If the visitor doesn’t have JavaScript enabled, they will still see all your portfolio items, which is also good for SEO purposes.

Making a CSS3 Animated Menu Posted on May 3rd, 2011



CSS

DemoDownload In this short tutorial, we will be using the power of CSS3 effects and transitions, to build a JavaScriptfree animated navigation menu which you can use to add a polished look to your website or template. We will be using some neat features such as the :target pseudo selector and :after elements.

The HTML The first step is to define the HTML backbone of the website. We are using HTML5 tags extensively, so we will need to include the HTML5 enabling script for IE in the head section of the document. As it is enclosed in a conditional comment, it is only going to be requested in IE browsers and will not affect the performance of the others:

index.html 01

<!DOCTYPE html>

02

<html>

03 04

<head> <meta charset="utf-8" />

05 06

<title>CSS3 Animated Navigation Menu | Tutorialzine Demo</title>

07 08

<!-- Our CSS stylesheet file -->

09

<link rel="stylesheet" href="assets/css/styles.css" />

10 11

<!-- Including the Lobster font from Google's Font Directory -->

12

<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Lobster " />

13 14

<!-- Enabling HTML5 support for Internet Explorer -->

15 16 17 18

<!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js "></script> <![endif]--> </head>

19 20

<body>

21 22

<header>

23

<h1>CSS3 Animated Navigation Menu</h1>

24

<h2>&laquo; Read and download on Tutorialzine</h2>

25

</header>

26 27 28

<nav> <ul class="fancyNav">

29

<li id="home"><a href="#home" class="homeIcon">Home</a></li>

30

<li id="news"><a href="#news">News</a></li>

31

<li id="about"><a href="#about">About us</a></li>

32

<li id="services"><a href="#services">Services</a></li>

33

<li id="contact"><a href="#contact">Contact us</a></li>

34 35

</ul> </nav>

36 37 38

<footer>Looks best in Firefox 4, usable everywhere.</footer>

39 40

</body> </html>

You can notice that we are including a stylesheet from Google APIs. It contains a @fontface declaration and includes the Lobster font into our page, from Google’s Web Font directory, which has grown to include more than 100 wonderful open source fonts, generously hosted by Google. In the body of the document, we have the header , nav and footer HTML5 tags, which divide the page into three sections with semantic value. We will be concentrating on the UL element inside the nav tag. This is our navigation menu. The unordered list has a fancyNav class applied to it, which we will be using to limit the effect of the CSS styles that we will be writing in a moment. This will make the code more portable and limit any possible side effects. Another thing to point out is that each of the LI elements has an unique ID, linked to from the anchor elements inside them. This will enable us to use the :target pseudo-class to style the currently selected menu item. So lets move on to the CSS styles.

CSS3 Animated Navigation Menu

The CSS You might find it surprising that the navigation menu we are building does not use any images (except for the home icon – a transparent png). Everything is done with CSS3 gradients, box shadows, and multiple backgrounds. As for browser support, the menu works in the latest versions of Firefox, Chrome, Safari and Opera, while it is still usable in every IE version from 7 onwards. However, it does look best in Firefox 4, as it supports animating :before and :after pseudo elements via the transition property (other browsers are expected to follow suite). Our CSS styles are defined in assets/styles.css. I would suggest that you download the menu code from the button above, and open that file in a text editor. We will be focusing primarily on the navigation menu, so I will be skipping the boring parts of the file. Lets start styling the navigation menu! We first write the rules for the unordered list – targeted with thefancyNav class, and the li items: 01

.fancyNav{

02

/* Affects the UL element */

03

overflow: hidden;

04

display: inline-block;

05 06

border-radius: 4px;

07

-moz-border-radius: 4px;

08

-webkit-border-radius: 4px;

09 10

box-shadow: 0 0 4px rgba(255, 255, 255, 0.6);

11

-moz-box-shadow: 0 0 4px rgba(255, 255, 255, 0.6);

12

-webkit-box-shadow: 0 0 4px rgba(255, 255, 255, 0.6);

13

}

14 15 16

.fancyNav li{ /* Specifying a fallback color and we define CSS3 gradients for the major browsers: */

17 18

19

background-color: #f0f0f0; background-image: -webkit-gradient(linear,left top, left bottom,from(#fefefe), colorstop(0.5,#f0f0f0), color-stop(0.51, #e6e6e6));

20

background-image: -moz-linear-gradient(#fefefe 0%, #f0f0f0 50%, #e6e6e6 51%);

21

background-image: -o-linear-gradient(#fefefe 0%, #f0f0f0 50%, #e6e6e6 51%);

22

background-image: -ms-linear-gradient(#fefefe 0%, #f0f0f0 50%, #e6e6e6 51%);

23

background-image: linear-gradient(#fefefe 0%, #f0f0f0 50%, #e6e6e6 51%);

24

25

border-right: 1px solid rgba(9, 9, 9, 0.125);

26 27

/* Adding a 1px inset highlight for a more polished efect: */

28 29

box-shadow: 1px -1px 0 rgba(255, 255, 255, 0.6) inset;

30

-moz-box-shadow: 1px -1px 0 rgba(255, 255, 255, 0.6) inset;

31

-webkit-box-shadow: 1px -1px 0 rgba(255, 255, 255, 0.6) inset;

32 33

position:relative;

34 35

float: left;

36

list-style: none;

37

}

Notice the huge list of CSS3 gradient syntaxes. All recent versions of Firefox, Chrome and Safari support gradients. With Opera and IE 10 (currently in platform preview mode), also joining in with their latest versions. Initially there were two competing syntaxes, backed by Mozilla (Firefox) on one side and Webkit (Chrome and Safari) on the other, but Firefox’s gradient syntax has been agreed on as the industry standard. The next step is to use the :after pseudo element to create the dark shadows, displayed when you hover over a menu item: 01

.fancyNav li:after{

02 03

/* This creates a pseudo element inslide each LI */

04 05

content:'.';

06

text-indent:-9999px;

07

overflow:hidden;

08

position:absolute;

09

width:100%;

10

height:100%;

11

top:0;

12

left:0;

13

z-index:1;

14

opacity:0 ;

15 16

/* Gradients! */

17

18

background-image:-webkit-gradient(linear, left top, right top, from(rgba(168,168,168,0.5)),color-stop(0.5,rgba(168,168,168,0)), to(rgba(168,168,168,0.5)));

19

background-image:-moz-linear-gradient(left, rgba(168,168,168,0.5), rgba(168,168,168,0) 50%, rgba(168,168,168,0.5));

20

background-image:-o-linear-gradient(left, rgba(168,168,168,0.5), rgba(168,168,168,0) 50%, rgba(168,168,168,0.5));

21

background-image:-ms-linear-gradient(left, rgba(168,168,168,0.5), rgba(168,168,168,0) 50%, rgba(168,168,168,0.5));

22

background-image:linear-gradient(left, rgba(168,168,168,0.5), rgba(168,168,168,0) 50%, rgba(168,168,168,0.5));

23 24

/* Creating borders with box-shadow. Useful, as they don't affect the size of the element. */

25 26

box-shadow:-1px 0 0 #a3a3a3,-2px 0 0 #fff,1px 0 0 #a3a3a3,2px 0 0 #fff;

27

-moz-box-shadow:-1px 0 0 #a3a3a3,-2px 0 0 #fff,1px 0 0 #a3a3a3,2px 0 0 #fff;

28

-webkit-box-shadow:-1px 0 0 #a3a3a3,-2px 0 0 #fff,1px 0 0 #a3a3a3,2px 0 0 #fff;

29 30

/* This will create a smooth transition for the opacity property */

31 32

-moz-transition:0.25s all;

33

-webkit-transition:0.25s all;

34

-o-transition:0.25s all;

35

transition:0.25s all;

36

}

The :after declaration creates a real styleable element. It has a smooth horizontal gradient that darkens the menu item when hovered upon. As it is invisible by default (opacity is set to 0), we are using CSS3 transitions to animate it between zero and full opacity, triggered on hover. Unfortunately only Firefox supports animating pseudo elements at this moment, but other browsers are expected to soon introduce this feature.

The Menu Explained Next we will be using the :first-child and :last-child pseudo selectors to target the first and last menu items. 01

/* Treating the first LI and li:after elements separately */

02 03

.fancyNav li:first-child{

04 05

border-radius: 4px 0 0 4px; }

06 07

.fancyNav li:first-child:after,

08

.fancyNav li.selected:first-child:after{

09

box-shadow:1px 0 0 #a3a3a3,2px 0 0 #fff;

10

-moz-box-shadow:1px 0 0 #a3a3a3,2px 0 0 #fff;

11

-webkit-box-shadow:1px 0 0 #a3a3a3,2px 0 0 #fff;

12 13 14

border-radius:4px 0 0 4px; }

15 16

.fancyNav li:last-child{

17 18

border-radius: 0 4px 4px 0; }

19 20

/* Treating the last LI and li:after elements separately */

21 22

.fancyNav li:last-child:after,

23

.fancyNav li.selected:last-child:after{

24

box-shadow:-1px 0 0 #a3a3a3,-2px 0 0 #fff;

25

-moz-box-shadow:-1px 0 0 #a3a3a3,-2px 0 0 #fff;

26

-webkit-box-shadow:-1px 0 0 #a3a3a3,-2px 0 0 #fff;

27 28 29

border-radius:0 4px 4px 0; }

30 31

.fancyNav li:hover:after,

32

.fancyNav li.selected:after,

33

.fancyNav li:target:after{

34

/* This property triggers the CSS3 transition */

35

opacity:1;

36

}

Applying different styles to the first and last items is necessary, as we don’t want to display ugly borders that span outside the menu. We also round the appropriate corners of these elements. Note: You can add class=”selected” to a list item in order to make it selected/active by default. This is useful when building templates or generating the menu with a server-side language. After this we need to apply a fix to the menu. It is to hide the currently selected element when we hover on the menu again: 01

.fancyNav:hover li.selected:after,

02

.fancyNav:hover li:target:after{

03

/* Hides the targeted li when we are hovering on the UL */

04

opacity:0;

05

}

06 07

.fancyNav li.selected:hover:after,

08

.fancyNav li:target:hover:after{

09 10

opacity:1 !important; }

And lastly all that is left is to style the anchor elements that reside in the LIs. 01

/* Styling the anchor elements */

02 03

.fancyNav li a{

04

color: #5d5d5d;

05

display: inline-block;

06

font: 20px/1 Lobster,Arial,sans-serif;

07

padding: 12px 35px 14px;

08

position: relative;

09

text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.6);

10

z-index:2;

11

text-decoration:none !important;

12

white-space:nowrap;

13

}

14 15

.fancyNav a.homeIcon{

16

background:url('../img/home.png') no-repeat center center;

17

display: block;

18

overflow: hidden;

19

padding-left: 12px;

20

padding-right: 12px;

21

text-indent: -9999px;

22

width: 16px;

23

}

With this our animated CSS3 menu is complete!

To Wrap Up Having your navigation menu built entirely with CSS gives you a great deal of control. You can customize every part of the design by swapping a color value or the font. The most of the bulk in the code came from having to supply a separate declaration for each browser, something that will soon be a thing of the past.

How to Make AutoAdvancing Slideshows Posted on Jan 13th, 2011



jQuery

DemoDownload One of the most requested improvements over the tutorials presented on this site, when it comes to slideshows, is the ability to have the slides advance automatically. It is actually not that difficult to achieve this effect, and to demonstrate it, in this short tutorial we are going to make our HTML5 Slideshow auto advance with a few lines of jQuery.

The Idea As our slideshow already has a previous / next arrows, we can just have a JavaScript function execute periodically and “click” the next arrow for us. With jQuery we can easily simulate any event on any element with the help of the trigger() method like so: 1

$('#nextArrow').bind('click',function(){

2 3

alert("Clicked!"); });

4 5

$('#nextArrow').trigger('click');

6 7

// or alternatively:

8

// $('#nextArrow').click();

The snippet above will fire all the handlers for the click event and output the alert message. In the case with the slideshow, we don’t care what happens behind the scenes nor how the animation works, we just simulate a click with the mouse. This means that we could as well have the auto advancing script as an external, separate file. Combined with the setTimeout() JavaScript function we have all the tools necessary to make our slideshow transition automatically between the slides.

The Implementation Bearing the above in mind, here is the complete auto advance code.

autoadvance.js 01

$(window).load(function(){

02 03

// The window.load event guarantees that

04

// all the images are loaded before the

05

// auto-advance begins.

06 07

var timeOut = null;

08 09

$('#slideshow .arrow').click(function(e,simulated){

10 11

// The simulated parameter is set by the

12

// trigger method.

13 14

if(!simulated){

15 16

// A real click occured. Cancel the

17

// auto advance animation.

18 19

clearTimeout(timeOut);

20 21

} });

22 23

// A self executing named function expression:

24 25

(function autoAdvance(){

26 27

// Simulating a click on the next arrow.

28

$('#slideshow .next').trigger('click',[true]);

29 30

// Schedulling a time out in 5 seconds.

31

timeOut = setTimeout(autoAdvance,5000);

32

})();

33 34

});

Notice that we are passing an array parameter to the trigger method on line 28. The element of this array is available to us as the simulated parameter on line 9. This helps us distinguish fake clicks from real ones. If a real one does occur, we stop the auto-advancement by clearing the timeout.

To Wrap Up

To use this script you just need to replace the selectors for the next arrow on line 28 and for both arrows on line 9. With these modifications you will be able to use this snippet to automate any slideshow (or any kind of presentation really) on your site by just including autoadvance.js with a script tag.

Client Testimonials Powered by PHP, XML and jQuery   

Posted on Dec 16th, 2010 CSS jQuery PHP

DemoDownload One of the easiest ways to boost up the sales of your products is to show the honest recommendations of people that have already purchased them. This is content that rarely changes, and you do not need a dedicated CMS system just to manage it. In this tutorial we are going to build a XML backed testimonial viewer, which, along with jQuery, can display the set on your product pages.

HTML The first step is to lay down the HTML markup of the page. We are setting up a simple one-page site so we can get a better feel of the testimonial viewer in action.

index.php 01

<!DOCTYPE html>

02 03

<html>

04

<head>

05

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

06

<title>Client Testimonials Powered by PHP and XML</title>

07 08

<link rel="stylesheet" type="text/css" href="css/styles.css" />

09 10

</head>

11

<body>

12

13

<div id="page">

14

15

<div id="topBar" >

16

<div id="logo">

17

</div>

18 19

<ul id="navigation">

20

<li><a href="#">Home</a></li>

21

<li><a href="#">About</a></li>

22

<li><a href="#">Buy Now!</a></li>

23 24

</ul> </div>

25 26 27 28

<div id="iPhone"> <p>Our new awesome iPhone App is available on the appstore.</p> </div>

29 30

<div id="testimonials">

31

<ul>

32

<!-- Generation of the testimonials takes place here -->

33

</ul>

34 35

</div>

36

</div>

37 38

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js "></script>

39

<script src="js/script.js"></script>

40 41

</body>

42

</html>

At the top of the document, we are including styles.css, the stylesheet for the page, and just before the closing body tag, we are including the jQuery library and our script.js file, which is discussed in the last step of the tutorial. The #testimonials div is where the magic happens. It is going to hold the client testimonials in the form of LI elements. Only the first testimonial is going to be shown on page load, and the rest will be displayed consecutively with a jQuery fade animation.

Client Testimonials with PHP, XML and jQuery

PHP Before inspecting the generation of the testimonials, lets take a look at the XML file that powers it.

testimonials.xml

01

<?xml version="1.0" encoding="utf-8"?>

02 03 04

<testimonials> <item>

05

<content>This has to be the most awesome app I've ever used!</content>

06

<author-name>John Doe</author-name>

07

<author-url>jdoe.com</author-url>

08

</item>

09

<item>

10

<content>Simply amazing! It solved my problem. I highly recommend it.</content>

11

<author-name>John Smith</author-name>

12

<author-url>smith.com</author-url>

13

</item>

14

<item>

15 16 17 18

<content>A tremendous success. It is like walking on sunshine compared to its competitors.</content> <author-name>John Smith</author-name> </item> </testimonials>

The schema of this file is simple – the root testimonials element holds a number of items. Each item hascontent, author-name and author-url items, where the last one is optional, as you can see from the last testimonial. You can include an arbitrary number of testimonials by just adding more items to this xml file. But how are we going to transform this into valid HTML? We could parse it with PHP and loop through the items, stitching together the markup, but there is an alternative approach with applying a XSLT stylesheet. This is a special XML based language, which allows us to transform a regular XML file into HTML.

transformations.xml 01

<?xml version="1.0" encoding="utf-8"?>

02 03

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform ">

04

<xsl:output method="html" encoding="utf-8" indent="no"/>

05 06

<!-- Matching the testimonials (root) element -->

07

<xsl:template match="/testimonials">

08

<!-- Using a for-each to loop through all the "item" elements -->

09

<xsl:for-each select="item">

10 11

<!-- This markup is going to be printed -->

12

<li>

13

<p class="text">

14

<!-- Value-of prints the value of the select attribute -->

15

<xsl:value-of select="content"/>

16

</p>

17 18 19

<p class="author"> <xsl:value-of select="author-name"/>

20 21

<!-- Using an "if" statement to check whether the URL field exists -->

22

<xsl:if test="author-url != '' ">

23

<xsl:value-of select="', '"/>

24

<a>

25

<!-- Creating an href attribute in the hyperlink -->

26

<xsl:attribute name="href">

27

<!-- Using the concat function -->

28

<xsl:value-of select="concat('http://',author-url)"/>

29

</xsl:attribute>

30 31

<xsl:value-of select="author-url"/>

32

</a>

33 34 35

</xsl:if> </p> </li>

36 37 38

</xsl:for-each> </xsl:template>

39 40

</xsl:stylesheet>

All the standard programming constructs are supported. You can use for-each loops, if statements and you can even call built in functions (you can learn more at this XSLT documentation site). What we did here, in effect, is to extract the transformation logic from PHP and put it in a separate, presentation file. There are two approaches when it comes to applying this XSL stylesheet. You can just include it in the XML file itself and leave it to the web browser to generate the HTML markup (all modern browsers support XSL transformations), or do it on the server side. Luckily, PHP has great support for XSL and it is really easy to use.

index.php 01

$xmlFile = 'xml/testimonials.xml';

02

$xslFile = 'xml/transform.xml';

03 04

$doc = new DOMDocument();

05

$xsl = new XSLTProcessor();

06 07

$doc->load($xslFile);

08

$xsl->importStyleSheet($doc);

09 10

$doc->load($xmlFile);

11

echo $xsl->transformToXML($doc);

The snippet above resides in the #testimonial div of index.php. It prints a set of LI elements after applying the XSL stylesheet to the XML document with all the testimonials. To the browser (and search spiders) everything looks like a regular HTML page.

jQuery Powered Client Testimonials Viewer

CSS Now that our markup is generated, lets style it. As the subject of the tutorial is primarily the backend, we will only take a brief look at the CSS code.

styles.css

01

#page{

02

width:800px;

03

margin: 0 auto 120px;

04

}

05 06

#topBar{

07

height:62px;

08

position:relative;

09

}

10 11

#logo{

12

width:194px;

13

height:62px;

14

position:absolute;

15

top:0;

16

left:0;

17

background:url('../img/logo.jpg') no-repeat;

18

}

19 20

#navigation{

21

position:absolute;

22

list-style:none;

23

right:0;

24

top:15px;

25

}

26 27

#navigation li{ display:inline;}

28 29

#navigation li a{

30

text-decoration:none;

31

font-weight:bold;

32

float:left;

33

padding:10px;

34

margin-right:10px;

35

font-size: 17px;

36

}

37 38

#iPhone{

39

height:400px;

40

margin:60px auto 0;

41

background:url('../img/iPhone.png') no-repeat;

42

}

43 44

#iPhone p{ display:none;}

45 46

#testimonials{

47

width: 375px;

48

padding: 45px 45px 35px 90px;

49

background:url('../img/quotes.png') no-repeat 20px 20px rgba(178,178,169,0.2);

50

min-height:90px;

51 52

-moz-border-radius:12px;

53

-webkit-border-radius:12px;

54

border-radius:12px;

55

}

56 57

#testimonials li{ display:none;}

58

#testimonials li:first-child{ display:block;}

59 60

#testimonials ul{ list-style:none;}

61

#testimonials p.text{ font-size:24px;}

62 63

#testimonials p.author{

64

color: #878787;

65

font-size: 16px;

66

font-style: italic;

67

text-align: right;

68

margin-top:10px;

69

}

70 71

#testimonials p.author a,

72

#testimonials p.author a:visited{

73 74

color:#6aa42a; }

The code above styles the page, and hides all the testimonials (which are simply LI elements inside of the main UL). After this, by using the first-child selector, we show the first one by default. It will be down to our jQuery code to cycle through the rest and show them consecutively.

jQuery In the jQuery part of the tutorial, we will create a simple script that will loop through the testimonials and show them one by one with a fade-in animation.

script.js 01

$(document).ready(function(){

02 03

// Hiding all the testimonials, except for the first one.

04

$('#testimonials li').hide().eq(0).show();

05 06

// A self executing named function that loops through the testimonials:

07

(function showNextTestimonial(){

08 09 10

// Wait for 7.5 seconds and hide the currently visible testimonial: $('#testimonials li:visible').delay(7500).fadeOut('slow',function(){

11 12

// Move it to the back:

13

$(this).appendTo('#testimonials ul');

14 15

// Show the next testimonial:

16

$('#testimonials li:first').fadeIn('slow',function(){

17 18

// Call the function again:

19

showNextTestimonial();

20

});

21

});

22

})();

23 24

});

By increasing the value passed to the delay method, you can control the screen time for each testimonial. Moving the active one to the back (instead of keeping an index) simplifies the function implementation and allows us to call showNextTestimonial recursively. With this our Client Testimonials viewer is complete!

Conclusion You can use this script as a quick solution to displaying testimonials on your product pages. You can even modify it to include ratings, stars, reviews, and other kinds of custom data. At the end, it is all down to editing an XML file.

Coding a CSS3 & HTML5 One-Page Website Template  

Posted on Feb 16th, 2010 CSS jQuery

DemoDownload Web development is an area in which you have to keep up with the latest technologies and techniques, so that you are at the top of your game. And no wonder – this is an area which changes with an amazing pace. What is the standard now will be obsolete in just a couple of years. But changes do not come from nowhere. The early adopters are already using what we are going to use day-to-day a few years from now. One of these technologies is HTML5 – the new version of the fundamental language of the web. Today we are making a HTML5 web template, using some of the new features brought by CSS3 and jQuery, with the scrollTo plug-in. As HTML5 is still a work in progress, you can optionally download aXHTML version of the template here.

Step 1 – The Design Every design process starts with an initial idea which you later build upon. At this stage, designers usually go with programs such as Photoshop, to work on the details and see how it will all fit together.

Photoshop Design After this, the design is hand coded with HTML and CSS going hand by hand, moving from designing the background, colors and fonts, to detail work on the content section.

Step 2 – HTML It is a good time to note, that HTML5 is still a work in progress. It will remain so probably till around2022 (I am absolutely serious about this). However some parts of the standard are complete, and can be used today. In this tutorial, we are using a few of the tags introduced with this new version of HTML:  header – wraps your page header;  footer – wraps your page footer;  section – groups content into sections (e.g. main area, sidebar etc);  article – separates the individual articles from the rest of the page;  nav – contains your navigation menu;  figure – usually contains an image used as an illustration for your article. These are used exactly as you would use normal divs. With the difference being that these tags organize your page semantically. In other words, you can present your content in such a way, that the subject matter of your page can be more easily determined. As a result services, such as search engines, will bring you more targeted visitors and thus boost your revenue (and theirs actually). However, there are some implications in using HTML5 today. One of the most notable is the IE family of browsers, which does not support these tags (it can be fixed with a simple JavaScript include file though). This is why you should base your decision for moving to HTML5 on your site’s audience. And just for this purpose, we are releasing a pure XHTML version of this template as well.

template.html – Head section 01

<!DOCTYPE html> <!-- The new doctype -->

02 03

<html>

04

<head>

05 06

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

07 08

<title>Coding A CSS3 &amp; HTML5 One Page Template | Tutorialzine demo</title>

09 10

<link rel="stylesheet" type="text/css" href="styles.css" />

11 12 13

<!-- Internet Explorer HTML5 enabling script: -->

14

<!--[if IE]>

15

<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js "></script>

16

<style type="text/css">

17 18

.clear {

19

zoom: 1;

20

display: block;

21

}

22 23

</style>

24 25

<![endif]-->

26 27

</head>

You can notice the new <DOCTYPE> at line one, which tells the browser that the page is created with the HTML5 standard. It is also much shorter and easier to remember than older doctypes. After specifying the encoding of the document and the title, we move on to including a special JS file that will enable Internet Explorer (any version) to render HTML5 tags properly. Again, this means that if a visitor is using IE and has JavaScript disabled, the page is going to show all messed up. This is why, depending on your audience, you should consider the regular XHTML version of this template, which works in any browser and is released free for all of our readers here.

template.html – Body Section 01

<body>

02 03

<section id="page"> <!-- Defining the #page section with the section tag -->

04 05 06

<header> <!-- Defining the header section of the page with the appropriate tag -->

07

<h1>Your Logo</h1>

08 09

<h3>and a fancy slogan</h3>

10

11

<nav class="clear"> <!-- The nav link semantically marks your main site navigation -->

12 13

<ul>

14 15

<li><a href="#article1">Photoshoot</a></li>

16

<li><a href="#article2">Sweet Tabs</a></li>

17

<li><a href="#article3">Navigation Menu</a></li>

18 19

</ul>

20 21

</nav>

22 23

</header>

Here we use the new section tags, which divide your page into separate semantic sections. Outermost is the #page section which is set to a width of 960px in the style sheet (a fairly standard width with older computer displays in mind). After this comes the header tag and the navigation tag. Notice the href attributes of the links – the part after the hash symbol # corresponds to the ID of thearticle we want to scroll to.

template.html – Article 01

<!-- Article 1 start -->

02 03

<div class="line"></div> <!-- Dividing line -->

04

05

<article id="article1"> <!-- The new article tag. The id is supplied so it can be scrolled into view. -->

06 07

<h2>Photoshoot Effect</h2>

08 09

<div class="line"></div>

10 11

<div class="articleBody clear">

12

13

<figure> <!-- The figure tag marks data (usually an image) that is part of the article -->

14 15 1 6

<a href="http://tutorialzine.com/2010/02/photo-shoot-css-jquery/"> <img src="http://cdn.tutorialzine.com/img/featured/641.jpg " width="620"heigh t="340" /></a>

17 18

</figure>

19

20

<p>In this tutorial, we are creating a photo shoot effect with our just-released PhotoShoot jQuery plug-in. With it you can convert a regular div on the page into a photo shooting stage simulating a camera-like feel.</p>

21 22

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer luctus quam quis .... </p>

23 24

</div>

25 26

</article>

27 28

<!-- Article 1 end -->

The markup above is shared between all of the articles. First is the dividing line (the best solution semantically would be an <hr> line, which in HTML5 has the added role of a logical dividing element, but unfortunately it is impossible to style in a cross-browser fashion, so we will stick with a DIV). After this we have the new article tag, with an unique ID, which is used by the navigation to scroll the page. Inside we have the title of the article, two paragraphs and the new figure tag, which marks the use of images in the article.

template.html – Footer 01

<footer> <!-- Marking the footer section -->

02 03

<div class="line"></div>

04 05

<p>Copyright 2010 - YourSite.com</p> <!-- Change the copyright notice -->

06

<a href="#" class="up">Go UP</a>

07

<a href="http://tutorialzine.com/" class="by">Template by Tutorialzine</a>

08 09

</footer>

10 11

</section> <!-- Closing the #page section -->

12 13

<!-- JavaScript Includes -->

14 15

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js "></script>

16

<script src="jquery.scrollTo-1.4.2/jquery.scrollTo-min.js"></script>

17

<script src="script.js"></script>

18 19

</body>

20 21

</html>

Lastly, we have the footer tag, which does exactly what you expect it to do. At the bottom of the page are the rest of the JavaScript includes, which add the jQuery library and the scrollTo plug-in, which we are going to use in the next steps.

An HTML5 & CSS3 Website Template

Step 3 – CSS As we are using HTML5, we have to take some extra measures with the styling. The tags that this new version of HTML introduces, are not yet provided with a default styling. This is however easily fixed with a couple of lines of CSS code and the page works and looks as it is supposed to:

styles.css – Part 1 01

header,footer,

02

article,section,

03

hgroup,nav,

04

figure{

05

/* Giving a display value to the HTML5 rendered elements: */

06

display:block;

07

}

08 09

article .line{

10

/* The dividing line inside of the article is darker: */

11

background-color:#15242a;

12

border-bottom-color:#204656;

13

margin:1.3em 0;

14

}

15 16

footer .line{

17 18

margin:2em 0; }

19 20

nav{

21

background:url(img/gradient_light.jpg) repeat-x 50% 50% #f8f8f8;

22

padding:0 5px;

23

position:absolute;

24

right:0;

25

top:4em;

26

27

border:1px solid #FCFCFC;

28 29

-moz-box-shadow:0 1px 1px #333333;

30

-webkit-box-shadow:0 1px 1px #333333;

31

box-shadow:0 1px 1px #333333;

32

}

33 34

nav ul li{

35 36

display:inline; }

37 38

nav ul li a,

39

nav ul li a:visited{

40

color:#565656;

41

display:block;

42

float:left;

43

font-size:1.25em;

44

font-weight:bold;

45

margin:5px 2px;

46

padding:7px 10px 4px;

47

text-shadow:0 1px 1px white;

48

text-transform:uppercase;

49 50

}

51

nav ul li a:hover{

52

text-decoration:none;

53

background-color:#f0f0f0;

54

}

55 56

nav, article, nav ul li a,figure{

57

/* Applying CSS3 rounded corners: */

58

-moz-border-radius:10px;

59

-webkit-border-radius:10px;

60

border-radius:10px;

61

}

We basically need to set the display value of the new tags to block, as you can see from the first couple of lines. After this we can style them as we would do with regular divs. We style the horizontal lines, the articles, and the navigation buttons, with the latter organized as an unordered list inside of the nav tag. At the bottom we assign the border-radius property for four different types of elements of once, which saves a lot of code.

styles.css – Part 2 01

/* Article styles: */

02 03

#page{

04

width:960px;

05

margin:0 auto;

06

position:relative;

07

}

08 09 10

article{ background-color:#213E4A;

11

margin:3em 0;

12

padding:20px;

13 14 15

text-shadow:0 2px 0 black; }

16 17

figure{

18

border:3px solid #142830;

19

float:right;

20

height:300px;

21

margin-left:15px;

22

overflow:hidden ;

23 24

width:500px; }

25 26

figure:hover{

27

-moz-box-shadow:0 0 2px #4D7788;

28

-webkit-box-shadow:0 0 2px #4D7788;

29

box-shadow:0 0 2px #4D7788;

30

}

31 32 33

figure img{ margin-left:-60px;

34

}

35 36

/* Footer styling: */

37 38

footer{

39

margin-bottom:30px;

40

text-align:center;

41

font-size:0.825em;

42

}

43 44

footer p{

45

margin-bottom:-2.5em;

46

position:relative;

47

}

48 49

footer a,footer a:visited{

50

color:#cccccc;

51

background-color:#213e4a;

52

display:block;

53

padding:2px 4px;

54

z-index:100;

55

position:relative;

56 57

}

58

footer a:hover{

59

text-decoration:none;

60

background-color:#142830;

61

}

62 63 64

footer a.by{ float:left ;

65 66

}

67 68

footer a.up{

69 70

float:right; }

In the second part of the code, we apply more detailed styling to the elements. A width for the pagesection, a hover property for the figure tag and styles for the links inside of the footer. There are also a few styles that are not included here, but you can see them in styles.css. Now lets continue with the next step.

Structure Of The Page - HTML5 Tags

Step 4 – jQuery To enhance the template, we will create a smooth scrolling effect once a navigation link has been clicked, using the scrollTo jQuery plug-in that we included in the page earlier. To make it work we just need to loop through the links in the navigation bar (and the UP link in the footer) and assign an onclick event which will trigger the $.srollTo() function, which is defined by the plug-in.

script.js 01 02

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

03 04

$('nav a,footer a.up').click(function(e){

05 06

// If a link has been clicked, scroll the page to the link's hash target:

07 08

$.scrollTo( this.hash || 0, 1500);

09

e.preventDefault();

10

});

11 12

});

With this our template is complete!

Wrapping it up In this tutorial, we leveraged the new semantic features provided by HTML5, to design and code a one-page web template. You can use it for free both personally and commercially, providing you leave the back link intact.

Making A Cool Login System With PHP, MySQL & jQuery    

Posted on Oct 17th, 2009 CSS jQuery MySQL PHP

DemoDownload

Introduction Today we are making a cool & simple login / registration system. It will give you the ability to easily create a member-only area on your site and provide an easy registration process. It is going to be PHP driven and store all the registrations into a MySQL database. To add the needed flair, we are using the amazing sliding jQuery panel, developed by Web-kreation.

Step 1 – MySQL First we have to create the table that will hold all the registrations. This code is available in table.sql.

table.sql 01

--

02

-- Table structure for table `tz_members`

03

--

04 05

CREATE TABLE `tz_members` (

06

`id` int(11) NOT NULL auto_increment,

07

`usr` varchar(32) collate utf8_unicode_ci NOT NULL default '',

08

`pass` varchar(32) collate utf8_unicode_ci NOT NULL default '',

09

`email` varchar(255) collate utf8_unicode_ci NOT NULL default '',

10

`regIP` varchar(15) collate utf8_unicode_ci NOT NULL default '',

11

`dt` datetime NOT NULL default '0000-00-00 00:00:00',

12

PRIMARY KEY (`id`),

13 14

UNIQUE KEY `usr` (`usr`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Notice that we’ve defined the id as an integer with auto_increment – it is automatically assigned to every site member. Also, we’ve defined usr as an unique key – no two users with the same usernames are allowed. We later use this in the registration to determine whether the username has been taken. After you create the table, do not forget to fill in your database credentials in connect.php so you can run the demo on your own server.

Step 2 – XHTML First, we have to incorporate Web-kreation’s form into our page.

demo.php 001

<!-- Panel -->

002

<div id="toppanel">

003 004

<div id="panel">

005

<div class="content clearfix">

006

<div class="left">

007

<h1>The Sliding jQuery Panel</h1>

008

<h2>A register/login solution</h2>

009

<p class="grey">You are free to use this login and registration system in you sites!</p>

010

<h2>A Big Thanks</h2>

011

<p class="grey">This tutorial was built on top of <a href="http://webkreation.com/index.php/tutorials/nice-clean-sliding-login-panel-built-withjquery" title="Go to site">Web-Kreation</a>'s amazing sliding panel.</p>

012

</div>

013 014

<?php

015

if(!$_SESSION['id']):

016

// If you are not logged in

017

?>

018 019

<div class="left">

020

<!-- Login Form -->

021

<form class="clearfix" action="" method="post">

022

<h1>Member Login</h1>

023 024

<?php

025

if($_SESSION['msg']['login-err'])

026

{

027

echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';

028

unset($_SESSION['msg']['login-err']);

029

// This will output login errors, if any

030

}

031

?>

032 033

<label class="grey" for="username">Username:</label>

03 4

<input class="field" type="text" name="username" id="username" value="" size="23" />

035

<label class="grey" for="password">Password:</label>

036

<input class="field" type="password" name="password" id="password" size="23" />

03 7

<label><input name="rememberMe" id="rememberMe" type="checkbox" checked="ch ecked" value="1" /> &nbsp;Remember me</label>

038

<div class="clear"></div>

039

<input type="submit" name="submit" value="Login" class="bt_login" />

040

</form>

041 042

</div>

043 044

<div class="left right">

045 046

<!-- Register Form -->

047 048

<form action="" method="post">

049

<h1>Not a member yet? Sign Up!</h1>

050 051

<?php

052 053

if($_SESSION['msg']['reg-err'])

054

{

055

echo '<div class="err">'.$_SESSION['msg']['reg-err'].'</div>';

056

unset($_SESSION['msg']['reg-err']);

057

// This will output the registration errors, if any

058

}

059 060

if($_SESSION['msg']['reg-success'])

061

{

062

echo '<div class="success">'.$_SESSION['msg']['reg-success'].'</div>';

063

unset($_SESSION['msg']['reg-success']);

064 065

// This will output the registration success message }

066 067

?>

068 069

<label class="grey" for="username">Username:</label>

07 0

<input class="field" type="text" name="username" id="username" value="" size="23" />

071

<label class="grey" for="email">Email:</label>

072

<input class="field" type="text" name="email" id="email" size="23" />

073

<label>A password will be e-mailed to you.</label>

074

<input type="submit" name="submit" value="Register" class="bt_register" />

075

</form>

076 077

</div>

078 079

<?php

080

else:

081

// If you are logged in

082

?>

083 084

<div class="left">

085

<h1>Members panel</h1>

086

<p>You can put member-only data here</p>

087

<a href="registered.php">View a special member page</a>

088

<p>- or -</p>

089

<a href="?logoff">Log off</a>

090

</div>

091

<div class="left right">

092

</div>

093 094

<?php

095

endif;

096

// Closing the IF-ELSE construct

097

?>

098 099

</div>

100

</div> <!-- /login -->

101 102

<!-- The tab on top -->

103

<div class="tab">

104

<ul class="login">

105

<li class="left">&nbsp;</li>

106

<li>Hello <?php echo $_SESSION['usr'] ? $_SESSION['usr'] : 'Guest';?>!</li>

107

<li class="sep">|</li>

108

<li id="toggle">

109

<a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Open Panel':'Log In | Register';?></a>

110

<a id="close" style="display: none;" class="close" href="#">Close Panel</a>

111

</li>

112

<li class="right">&nbsp;</li>

113

</ul>

114

115

</div> <!-- / top ->

116

</div> <!--panel -->

At several places in this code, there are some PHP operators that check whether $_SESSION['usr'] or$_SESSION['id'] are defined. This is true only if the page visitor is logged in the site, which allows us to show specific content to site members. We will cover it in detail in a moment. After the form, we put the rest of the page. 01

<div class="pageContent">

02 03

<div id="main">

04 05

<div class="container">

06

<h1>A Cool Login System</h1>

07

<h2>Easy registration management with PHP &amp; jQuery</h2>

08

</div>

09 10

<div class="container">

11

<p>This is a ...</p>

12

<div class="clear"></div>

13 14

</div>

15 16

</div>

Nothing special here. Lets continue with the PHP backend.

The login system

Step 3 – PHP It is time to convert the form into a complete registration and login system. To achieve it, we will need more than the usual amount of PHP. I’ll divide the code into two parts. If you plan to add more code, it would be a good idea to split it into several files which are included when needed. This aids the development of large projects and allows code reuse in different parts of a site. But lets see how we’ve done it here.

demo.php 01

define('INCLUDE_CHECK',true);

02 03

require 'connect.php';

04

require 'functions.php';

05 06

// Those two files can be included only if INCLUDE_CHECK is defined

07 08

session_name('tzLogin');

09

// Starting the session

10 11

session_set_cookie_params(2*7*24*60*60);

12

// Making the cookie live for 2 weeks

13 14

session_start();

15 16

if($_SESSION['id'] && !isset($_COOKIE['tzRemember']) && !$_SESSION['rememberMe'])

17

{

18

// If you are logged in, but you don't have the tzRemember cookie (browser restart)

19

// and you have not checked the rememberMe checkbox:

20 21

$_SESSION = array();

22

session_destroy();

23 24 25

// Destroy the session }

26 27

if(isset($_GET['logoff']))

28

{

29

$_SESSION = array();

30

session_destroy();

31

header("Location: demo.php");

32

exit;

33 34

}

35

if($_POST['submit']=='Login')

36

{

37

// Checking whether the Login form has been submitted

38 39

$err = array();

40

// Will hold our errors

41 42

if(!$_POST['username'] || !$_POST['password'])

43

$err[] = 'All the fields must be filled in!';

44 45

if(!count($err))

46

{

47

$_POST['username'] = mysql_real_escape_string($_POST['username']);

48

$_POST['password'] = mysql_real_escape_string($_POST['password']);

49

$_POST['rememberMe'] = (int)$_POST['rememberMe'];

50 51

// Escaping all input data

52

53

$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));

54 55

if($row['usr'])

56

{

57

// If everything is OK login

58 59

$_SESSION['usr']=$row['usr'];

60

$_SESSION['id'] = $row['id'];

61

$_SESSION['rememberMe'] = $_POST['rememberMe'];

62 63

// Store some data in the session

64 65

setcookie('tzRemember',$_POST['rememberMe']);

66

// We create the tzRemember cookie

67

}

68

else $err[]='Wrong username and/or password!';

69

}

70 71

if($err)

72

$_SESSION['msg']['login-err'] = implode('<br />',$err);

73

// Save the error messages in the session

74 75

header("Location: demo.php");

76

exit;

77

}

Here the tzRemember cookie acts as a control whether we should log-off users that have not marked the “remember me” checkbox. If the cookie is not present (due to browser restart) and the visitor has not checked the remember me option, we destroy the session. The session itself is kept alive for two weeks (as set by session_set_cookie_params). Lets see the second part of demo.php. 01

else if($_POST['submit']=='Register')

02

{

03

// If the Register form has been submitted

04

$err = array();

05 06

if(strlen($_POST['username'])<4 || strlen($_POST['username'])>32)

07

{

08 09

$err[]='Your username must be between 3 and 32 characters!'; }

10 11

if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username']))

12

{

13 14

$err[]='Your username contains invalid characters!'; }

15 16

if(!checkEmail($_POST['email']))

17

{

18 19

$err[]='Your email is not valid!'; }

20 21

if(!count($err))

22

{

23 2 4 25

// If there are no errors $pass = substr(md5($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000)),0 ,6); // Generate a random password

26 27

$_POST['email'] = mysql_real_escape_string($_POST['email']);

28

$_POST['username'] = mysql_real_escape_string($_POST['username']);

29

// Escape the input data

30 31

mysql_query("

INSERT INTO tz_members(usr,pass,email,regIP,dt)

32

VALUES(

33

'".$_POST['username']."',

34

'".md5($pass)."',

35

'".$_POST['email']."',

36

'".$_SERVER['REMOTE_ADDR']."',

37

NOW()

38

)");

39 40

if(mysql_affected_rows($link)==1)

41

{

42

send_mail( '[email protected]',

43

$_POST['email'],

44

'Registration System Demo - Your New Password',

45

'Your password is: '.$pass);

46

$_SESSION['msg']['reg-success']='We sent you an email with your new password!';

47

}

48

else $err[]='This username is already taken!';

49

}

50 51

if(count($err))

52

{

53

$_SESSION['msg']['reg-err'] = implode('<br />',$err);

54

}

55 56

header("Location: demo.php");

57

exit;

58

}

59 60

$script = '';

61

if($_SESSION['msg'])

62

{

63

// The script below shows the sliding panel on page load

64

$script = '

65

<script type="text/javascript">

66

$(function(){

67

$("div#panel").show();

68

$("#toggle a").toggle();

69

});

70

</script>';

71

}

We store all the encountered errors in an $err array, which is later assigned to a $_SESSION variable. This allows it to be accessible after a browser redirect. You may have noticed on some sites, that when you submit a form and later refresh the page, the data is sent all over again. This could become problematic as it could lead to a double registrations and unnecessary server load.

We use the header function to prevent this, by redirecting the browser to the same page. This starts a fresh view of the page, without the browser associating it with a form submit. The result is that, on page refresh, no data is sent. But as we use $_SESSION to store all the encountered errors it is important that we unset these variables, once we show the errors to the user. Otherwise they will be shown on every page view (the highlighted lines on the XHTML part of the tutorial). Also notice how we create an additional script (lines 60-70 of the second part of the PHP code) which shows the panel on page load, so that the messages are visible to the user. Now lets take a look at the CSS.

The registration / login system

Step 4 – CSS The sliding panel comes with its own style sheet. This means we are only left with creating the page styles.

demo.css 01

body,h1,h2,h3,p,quote,small,form,input,ul,li,ol,label{

02

/* The reset rules */

03

margin:0px;

04

padding:0px;

05

}

06 07

body{

08

color:#555555;

09

font-size:13px;

10

background: #eeeeee;

11

font-family:Arial, Helvetica, sans-serif;

12

width: 100%;

13

}

14 15

h1{

16

font-size:28px;

17

font-weight:bold;

18

font-family:"Trebuchet MS",Arial, Helvetica, sans-serif;

19

letter-spacing:1px;

20

}

21 22

h2{

23

font-family:"Arial Narrow",Arial,Helvetica,sans-serif;

24

font-size:10px;

25

font-weight:normal;

26

letter-spacing:1px;

27

padding-left:2px;

28

text-transform:uppercase;

29

white-space:nowrap;

30

margin-top:4px;

31

color:#888888;

32

}

33 34

#main p{

35 36

padding-bottom:8px; }

37 38

.clear{

39 40

clear:both; }

41 42

#main{

43

width:800px;

44

/* Centering it in the middle of the page */

45

margin:60px auto;

46

}

47 48 49

.container{ margin-top:20px;

50 51

background:#FFFFFF;

52

border:1px solid #E0E0E0;

53

padding:15px;

54 55

/* Rounded corners */

56

-moz-border-radius:20px;

57

-khtml-border-radius: 20px;

58

-webkit-border-radius: 20px;

59

border-radius:20px;

60

}

61 62

.err{

63 64

color:red; }

65 66

.success{

67 68

color:#00CC00; }

69 70

a, a:visited {

71

color:#00BBFF;

72

text-decoration:none;

73

outline:none;

74

}

75 76 77

a:hover{ text-decoration:underline;

78

}

79 80

.tutorial-info{

81

text-align:center;

82

padding:10px;

83

}

Step 5 – jQuery The sliding panel comes with its own jQuery files.

demo.php 0 1

<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquer y.min.js"></script>

02 03

<!-- PNG FIX for IE6 -->

04

<!-- http://24ways.org/2007/supersleight-transparent-png-in-ie6 -->

05

<!--[if lte IE 6]>

06

<script type="text/javascript" src="login_panel/js/pngfix/supersleight-min.js"></script>

07

<![endif]-->

08 09

<script src="login_panel/js/slide.js" type="text/javascript"></script>

10 11

<?php echo $script; ?>

First we include the jQuery library from Google’s CDN. Later comes a special fix for IE6 PNG transparency issues and lastly the panel’s script is included. At the bottom of the page is the $script variable – it shows the panel on page load if needed. With this our cool login system is complete!

Conclusion Today we learned how to use a fantastic form component and turn it into a functional log in / registration system. You are free to built upon this code and modify it any way you see fit.

A Stylish Navigation Menu With jQuery Posted on Sep 14th, 2009

 

CSS jQuery

DemoDownload

Introduction As you may know, the first 20 seconds of a new visitor’s interaction with a website determine whether they are going to stay or leave. This means you have to follow common design practices and put everything where the user would expect it to be. A crucial part of this process is developing an easy to use navigation menu. In this tutorial we are going to make a stylish CSS + XHTML navigation menu with the help of the jQuery library. So download the tutorial files above and keep on reading..

Step 1 – the XHTML The XHTML code is simple and search engine friendly.

index.html 01

<div id="menu-container">

02

<ul id="navigationMenu">

03

<li><a href="#" class="normalMenu">Home</a></li>

04

<li><a href="#" class="normalMenu">Services</a></li>

05

<li><a href="#" class="selectedMenu">Our clients</a></li>

06

<li><a href="#" class="normalMenu">The team</a></li>

07

<li><a href="#" class="normalMenu">About us</a></li>

08

<li><a href="#" class="normalMenu">Contact us</a></li>

09

</ul>

10

</div>

The entire navigation menu is basically one unordered list. You can introduce new menu items by just adding more LI elements and setting their respective text and target URLs. An important thing to note here is how you can mark a menu item as selected by default (or active) – just assign it the selectedMenu class (line 5). For example, here we are highlighting the “Our clients” page. You can set it up manually for a static site, or use PHP to do ti dynamically.

The navigation menu explained

Step 2 – jQuery As you can see from the illustration above, we are going to clone the set of links defined in our XHTML (the dark ones) and assign them the hoverMenu CSS class, which floats them above the default ones. This strategy has many advantages – firstly it keeps the XHTML cleaner, because you do not have to add those links manually to the page, and secondly it guarantees that you will have clean and working navigation regardless of the visitor’s javascript support – great for both usability and SEO. Now lets see what happens in our script.js.

script.js 01

$(document).ready(function(){

02

// executed after the page has finished loading

03 04

$('#navigationMenu li .normalMenu').each(function(){

// for each menu item

05 06

// create a duplicate hyperlink and position it above the current one

07

$(this).before($(this).clone().removeClass().addClass('hoverMenu'));

08 09

});

10 11

$('#navigationMenu li').hover(function(){

12 13

// we assign an action on mouse over

// using the hover method..

14

$(this).find('.hoverMenu').stop().animate({marginTop:'0px'},200);

15

// the animate method provides countless possibilities

16 17

},

18 19

function(){

20

// and an action on mouse out

21

$(this).find('.hoverMenu').stop().animate({marginTop:' -25px'},200);

22 23

});

24 25

});

Great, but what have we just done? First we used the $(‘document’).ready method to insure that the code is executed after the page has finished loading. Then we looped through all the links and cloned them, assigning a new CSS class – hoverMenu. After this we used the hover() method to easily add event handlers for both the mouseover and the mouseout event. Later we used the animate method – a really powerful tool in the jQuery arsenal. In this case we provided it with a new marginTop value and the duration of the effect. jQuery will handle all the animation. Note the use of the stop() method – it stops all currently active animations and thus prevents the stacking of different animation effects on top of each other guaranteeing a smooth user experience.

Step 3 – the CSS Lets take a look at our CSS style sheet.

demo.css 01

/* Page styles */

02

03

body,h1,h2,h3,p,td,quote,small,form,input,ul,li,ol,label{ better browser compatibility */

04

margin:0px;

05

padding:0px;

/* resetting some elements for

06

}

07 08

body{

/* styling the body */

09

margin-top:20px;

10

font-family:Arial, Helvetica, sans-serif;

11

color:#51555C;

12

height:100%;

13

font-size:12px;

14

}

15 16

/* Navigation menu styles */

17 18

ul{ /* the unordered list */

19

height:25px;

20

font-family:Arial, Helvetica, sans-serif;

21

font-size:12px;

22

}

23 24

ul li{

25

border:1px solid #444444;

26

display:inline-block;

27

float:left; /* floating the list items to the left */

28

height:25px;

29

list-style-type:none;

/* changing the display property */

/* disabling the list icon */

30 31

overflow:hidden;

/* hiding the overflowing content */

}

32 33

ul li a, ul li a:hover,

34

ul li a:visited{

35 36

text-decoration:none;

/* removing the underline text-decoration */

}

37 38

/* styling the links */

39

.normalMenu, .normalMenu:visited,

40

.hoverMenu, .hoverMenu:visited,

41

.selectedMenu,.selectedMenu:visited {/* these properties are shared between the classes */

42

outline:none;

43

padding:5px 10px;

44

display:block;

45

}

46 47

/* styles that are assigned individually */

48 49

.hoverMenu,.hoverMenu:visited,

50

.selectedMenu,.selectedMenu:visited {

51

margin-top:-25px;

52

background:url(img/grey_bg.gif) repeat-x #eeeeee;

53

color:#444444;

54

}

55 56

.selectedMenu,.selectedMenu:visited {

57 58

margin:0; }

59 60

.normalMenu, .normalMenu:visited{

61

color:white;

62

background:url(img/dark_bg.gif) repeat-x #444444;

63

}

As you can see, we have three main classes that define the looks of our navigation menu. normalMenu – for the normal state of the navigation links, hoverMenu – lighter link that slides down on hover,selectedMenu the active (selected) state. With this our stylish navigation menu is complete!

Conclusion In this tutorial I showed you how to create a stylish and user friendly navigation menu. You are free to use it in your sites and modify it in whatever fashion you find appropriate.

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close