Create a bullet-proof contact form

Note: This article has been marked for a quality review and will soon be updated.

Contact pages are usually one of the basic building blocks of any website, and while many simple feature an email address for spam bots to pick up and use, or even a handy 'mailto' link, the best ones feature a proper contact form. To make a bulletproof one we're going to need some thick glass and a riot shield PHP and JavaScript. Having those bad-boys on our side will ensure we can create a beautiful AJAX-enabled means of contact for our users. We also need to ensure our form will work on the rare occasion that a user has JavaScript turned-off *gasp* - I know, it's a scary thought, but I'm sure we'll figure something out!

So we'll start with some simple HTML to set out our fields, the following code is what we'll be working with:

<form id="contact" class="right" method="post" action="mail.php">
	<h3 class="hidden success"><br/>Message sent!</h3>
	
	<label>Name: <span class="warning right"></span>
		<input type="text" name="name" />
	</label>
	
	<label>Email: <span class="warning right"></span>
		<input type="text" name="email" />
	</label>

	<label>Message: <span class="warning right"></span>
		<textarea name="message"></textarea>
	</label>
	<input class="right" type="submit" value="Send" />
</form>

Aside from the obvious, the form features a few extra elements - namely the .warning elements - we'll see what they're for in a moment. I also assume that you have the class of .right set up to float elements to the right; if now, then you'll need to float the affected elements individually in your CSS. Right, that's the HTML sorted, lets take a look at the JavaScript for this puppy.

function validateEmail(email){ 
	 var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ 
	 return email.match(re); 
}

$('#contact').submit(function(){
	var name, email, message, errors;
	
	errors = 0;
	name = $('input[name=name]').val();
	email = $('input[name=email]').val();
	message = $('textarea[name=message]').val();
	
	$('.warning').text('');
	
	if(name==''){ $('input[name=name]').siblings('.warning').text('This field is required!'); errors++; }
	if(email==''){ $('input[name=email]').siblings('.warning').text('This field is required!'); errors++; }
	if(message==''){ $('textarea[name=message]').siblings('.warning').text('This field is required!'); errors++; }
	if(!validateEmail(email)){ $('input[name=email]').siblings('.warning').text('Please enter a valid email!'); errors++; }
	
	if(errors==0){
		var dataString = $(this).serialize() + '&js=true';
	
		$.ajax({
			url: 'contact-post.php',
			data: dataString,
			type: 'POST',
			success: function(data){
				$('form label, form input[type=submit]').slideUp(500, function(){
					$('form .success').hide().removeClass('hidden').slideDown(500);
				});
			}
		});
	}
	
	return false;
});

Now for the moment we'll ignore the validateEmail() function, and take a look at the form submission code. First off we set up some variables for the values in our form, this prevents us having to use longer code snippets and querying the DOM too much. Once we've got them set up we give the user the benefit of the doubt and remove any warning that may have previously been set by removing any text from the elements with the class of .warning. And then we validate the fields. The first three 'if' statements simply check that the user has entered a value in each field - if they haven't we tell them so, and increment our errors variable by 1. The last 'if' statement uses the validateEmail() function that we set earlier. There's no reason to worry if you don't understand how that function works, Regular Expressions are a world of their own. All we need to know, is that it tells us if the user has entered a valid email address.

Following our rather basic validation checks we then test to see if the form has passed - because we've been using our errors variable all along, if it's set to '0' we can rest assured nothing has gone wrong. If that's the case we serialise the form, and use a simple AJAX request to submit the data to our server. If our server is happy, we show our users a success message. Now all we need to do is set up our contact-post.php file, like so:

function redirect($hash){
	if($hash!='success'){
		echo 'Invalid ' . $hash;
	}else {
		echo 'Message sent!';
		echo '<meta http-equiv="refresh" content="0;url=http://example.com/">';
	}
	die();
}

if($_POST){
	if(empty($_POST['js'])){
		// Validate info here
		if(empty($_POST['name'])){ redirect('name'); }
		if(empty($_POST['email'])){ redirect('email'); }
		if(empty($_POST['message'])){ redirect('message');  }
		if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){ redirect('email'); }
	}
	
	$sendto = 'you@example.com';

	$name = $_POST['name'];
	$email = $_POST['email'];
	$phone = $_POST['phone'];
	$message = $_POST['message'];
	
	$to = $sendto;
	$subject = "[MySiteName] Message";
	
	$message = "
	<html>
	<head>
	<title>Contact form Submission</title>
	</head>
	<body>
	<p style='font-family:Arial, Helvetica, sans-serif; color:black;'>The following was sent by <strong>".$name." (Email: ".$email."):</strong></p>
	<p style='font-family:Arial, Helvetica, sans-serif; color:black; font-size:16px;'>".nl2br(stripslashes($message))."</p>
	
	<p style='font-family:Arial, Helvetica, sans-serif; color:black;'>(Sent on: ".gmdate('d\/m\/y').")</p>
	</body>
	</html>
	";
	
	$headers = "MIME-Version: 1.0" . "\r\n";
	$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
	$headers .= 'From: ' . $name;
	
	mail($to,$subject,$message,$headers);
	
	redirect('success');
}else {
        redirect('submission - no data entered!');
}

The function at the top will be used when we want to give the user some feedback - if they entered all the correct info, they'll be given a success message, and then redirected to your site in a timely fashion, otherwise they will be told what is wrong with their submission. Then we get to the guts of the script - we first make sure there is some data to play with - if there isn't we tell the user off, and if there is we go on to see if the user has JavaScript running. You may have noticed the little variable 'js' that we added to the serialised form back in our JavaScript - that is our way of finding out if the form is being submitted via an AJAX request in JavaScript - if the variable is empty, we let PHP validate our form's content - this is essentially identical to the JS code we used previously.

We then set up a really basic email, and send it to the address in the $sendto variable. Finally we redirect the user to the site. As a side note, do remember that this page will only be seen by users without JavaScript turned on.

And that's it! You now have a swanky contact form that, for all intents and purposes, is bullet-proof, but having said that, I wouldn't actually test that theory with a gun of any kind...

Prevent broken animations in jQuery

Note: This article has been marked for a quality review and will soon be updated.

I recently posted an article on Animating a Site's Loading using jQuery - a handy technique to spice up any site. But an issue that became apparent using this technique, along with some other animation methods, is that sometimes user interaction can prevent loading and other animations from finishing correctly, and possibly lead to pages that look broken because of it. This is the sort of thing that only user-testing will usually uncover, as many web-designers simply sit back and watch the animations, before actually interacting with the site. To explain what I mean I'll show you a basic example of navigation animations - and the one that prompted this article.

$('nav li').each(function(index){
    $(this).slideDown(200*(index+1));
});

$('nav li').hover(function(){
    $(this).stop().animate({'paddingTop':'10px'},200);
});

Now the code above works perfectly fine - it slides-down each list element in my navigation panel, and whenever a user rolls over one with their mouse the list element moves down by 10 pixels. Great, but we have a slight problem; namely, the stop() function. The code uses it to prevent an animation build up if a user quickly moves their mouse over multiple list elements for example, and for that it works very well. But because we are using a loading animation, if a user hovers over a list element before it has completed the the slide-down animation, the list element will be stuck in limbo, or rather, it won't finish sliding down.

This is caused by the fact that the hover() is bound to each list element at the same time that the animations are being executed. To solve this issue we need to come up with a way of waiting for the animations to complete before binding any events to our elements. One way of doing this might be to add a class to each element as it finishes it's loading, and then checking to see if the class exists before performing any events. But that approach will quickly clog up both your JavaScript, and HTML. To avoid messy code, we should instead only bind such events once the animation has completed.

To do that, we just make a simple alteration, like so:

$('nav li').each(function(index){
    $(this).slideDown(200*(index+1), function(){
        $(this).hover(function(){
            $(this).stop().animate({'paddingTop':'10px'},200);
        });
    });
});

The code above uses the callback function of the slideDown() function to wait until the animation completes. We then bind the hover event to each element individually, and we have ourselves a much better setup to prevent our sites breaking in the hands of hover-happy users.

Hide an element with jQuery whilst scrolling

Note: This article has been marked for a quality review and will soon be updated.

Today I came across an interesting problem that no amount of Google searches could solve. So I had to knuckle down and come up with a solution - and surprisingly it was much more simple that it had first appeared.

So the problem is hiding an element when a user is scrolling - it might be a menu, a header, or a picture of my cat, Sophie. Either way we can't just use the simple delay() function in jQuery to help us out - we need to use some raw JavaScript. To accomplish this we will create a variable into which we will place the current scroll amount of the page, we will then wait for a period of time, and check if that scroll amount has changed. If it has we will leave the element hidden, otherwise we'll show it to the user again.

And here's the rather simple code to do just that:

$(document).scroll(function(){
	$('section').fadeOut();
	
	var scrollA = $('body').scrollTop();
	
	setTimeout(function(){
		if(scrollA == $('body').scrollTop()){
			$('section').fadeIn();
		}
	}, 200);
});

And there we have it! A really simple effect made easy with a tiny bit of JavaScript.

You can check out the fiddle over here: http://jsfiddle.net/LJVMH/

Animate a site’s loading

Note: This article has been marked for a quality review and will soon be updated.

There are a lot of things we can do as web designers to improve the UX of a site, much of the time subtle animations can be added to add a bit of finesse to a page, and a new trend is that of adding animations to the loading of pages to make it look a bit better. So what do I mean by 'loading animations'? I'm not talking about the annoying "feature" of having a site load in a flash and then display a loading spinner while it actually pulls up the content using AJAX; rather adding a tiny amount of code to gain more control over how our site loads. But before we jump in to the code we need to remember a couple of things: first the animations can't take very long, after all we're trying to improve the user experience, so having a site take 5 seconds to load in will just frustrate the user. And second, as we will be using JavaScript for this, we need to add a fallback in case it's turned off.

Here's what we'll be creating (new window).

So to begin I've written up a very simple page, here's the HTML:

<!DOCTYPE HTML>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>Animated Loading</title>
	<!--[if IE]>
		<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->
	<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
	<div class="wrapper">
		<header>
			<h1 class="left">My Website</h1>
			<nav>
				<ul>
					<li>Home</li>
					<li>More</li>
					<li>About</li>
					<li>Contact</li>
				</ul>
			</nav>
		</header>
		<section class="hidden">
			<h2>Welcome</h2>
			<p>Yay for loading animations!</p>
		</section>
		<footer class="hidden">
			<p>Copyright goes here</p>
		</footer>
	</div>
</body>
</html>

Notice the use of the class "hidden" - that does exactly what you might think, and to make sure it actually works, let's hook up the CSS:

/* Globals */
.wrapper {
	max-width:1200px;
	display: block;
	margin:0 auto;
	padding:0 10px;
}

.hidden {
	display: none;
}

.left { float:left; }
.right { float:right; }

body {
	background: #dfdfdf;
}

/* Header */
header {
	overflow: hidden;
	position: relative;
	top:-145px;
}

h1 {
	background: #222;
	padding:50px;
	font-size: 2.5em;
	line-height: 0.4em;
	color: #fff;
}
		
nav {
	float: right;
}

	nav li {
		padding-top:52px;
		float: left;
		width:91px;
		text-align: center;
		height:90px;
		cursor: pointer;
		margin-right:2px;
		display: none;
	}
	
/* Sections */
section {
	margin-top:2%;
	padding:2%;
	background: #fff;
	overflow: hidden;
}
	
	section h2 {
		font-size: 1.25em;
		font-weight: bold;
	}

/* Footer */
footer {
	text-align: center;
	padding-top:10px;
}

Again, some very basic CSS to ensure it actually looks like a functional website. Notice how elements such as the 'nav li' elements are hidden using CSS (you might want to just add a class in the HTML, but if they are dynamically generated, this is your best bet).

If we open the page now we don't see very much, some would say it was blank, many people actually. This is what users without JavaScript enabled will see. So to remedy that we need to make use of the <noscript> tag in our header. Just before the closing <head> tag, add the following code:

<noscript>
	<style type="text/css">
		header {
			top:0px !important;
		}
		
		section, footer, nav li {
			display: block !important;
		}
	</style>
</noscript>

That code will only be executed if we don't have access to JavaScript, and so will force the elements we worked so hard to hide, to show up. Good stuff, we're not breaking the internet by requiring JavaScript! And on that note, let's write some.

Here's the code I wrote for the example - it's very basic, and executes within 2.45 seconds (but because some animations are in parallel it feels like 1.25 seconds). Make sure you include jQuery on your page, and then whack in the following code:

$(function(){
	/* Loading Animations */
	$('header').animate({'top':0},500, function(){
		$('nav li').each(function(index){
			$(this).slideDown(300*(index+1));
		});
		
		$('section, footer').fadeIn(750).removeClass('hidden');
	});
	

	$('a:link').click(function(){
		$('header').animate({'top':'-185px'},300);
		$('section, footer').fadeOut(300);
	});
});    		 

The first part of the that code waits for the DOM to be fully loaded, and then animates the header to slide in. When the header has finished showing up we cycle through the navigation's list elements, sliding them down at a growing animation length (notice the '+1' to ensure we don't multiply by zero). Once that's done we fade in any other elements we had hidden, and remove the class of 'hidden' - here you could use another each() cycle, but in the interests of speed I just stuck with a simple fade in effect. The next block of code is for links away from the page. We look for any links, and then whenever they are clicked, we quickly animate the contents of the page out in 0.3 seconds - I think this is just a nice touch. With a bit of tweaking of things like timings and the odd animation, you can make a visitor smile before they've even read what's on your site.

And that's how to improve the UX of your websites with subtle loading animations.

10 Best Practises for jQuery Beginners

Note: This article has been marked for a quality review and will soon be updated.

jQuery is the one of the most popular JavaScript frameworks available; it enables developers to write code that is easy to understand but that also allows really powerful functionality. There are a boat-load of tutorials out there on jQuery, and the documentation is awesome, but in this article I'll go over the things that all beginners should know about jQuery.

1) Document.ready

One thing that often catches newbies out is that their code doesn't seem to be having any effect on their page, despite all of it being correct. A major cause of this is that their jQuery code is attempting to access DOM elements before they exist. This can happen because developers place their JavaScript in the <head> of their pages, and so by the time the rest of the page has loaded jQuery doesn't know what's going on. The simple way to solve this issue is by telling jQuery to execute the code only when the DOM has finished loading, like so:

$(document).ready(function(){
	//Code goes here
});

But be warned, there are some circumstances where you shouldn't bother wrapping code in it. For example if you're clued-up about performance and already have all your code at the bottom of your page, it's unnecessary to use it, because all the elements already exist. Other exceptions might include wanting better code reusability - say for instance placing non-jQuery functions outside of the wrapping.

2) Cache elements

A lot of the time people write functions like:

$('.myelement').click(function(){
	$(this).doSomething();
	$(this).doSomethingElse();
	$(this).fadeOut(500);
});

And there isn't anything wrong with that. But if you started doing 10 things to the element once it were clicked it would start to look a little messy. To fix this it's a good idea to put the $(this) selector into a variable, like so:

$('.myelement').click(function(){
	var el = $(this);	
	el.doSomething();
	el.doSomethingElse();
	el.fadeOut(500);
});

This will give you less code to write in the long run, and using descriptive variable names will also help you keep focus on what you are manipulating. But more important than that is the performance increase - asking jQuery to return an element over and over as we did before wastes valuable performance - so caching will speed up your code!

3) Chaining

And the above brings me nicely to my next point - chaining. You can chain jQuery functions, meaning that you don't have to separate all those lovely functions, so the code I just wrote could actually look like:

$('.myelement').click(function(){
	$(this).doSomething().doSomethingElse().fadeOut(500);
});

And by just chaining those functions we have condensed 3 lines of code into 1.

4) AJAX

One reason why a number of developers like jQuery is because it has an excellent syntax for AJAX. In Javascript making AJAX requests is cumbersome and difficult to learn, but in jQuery it's pretty easy. So if you've taken the time to fade in messages to your users using jQuery, why not go ahead and submit forms using AJAX, thus creating a more cohesive user experience.

This is how it's done:

$('.myform').submit(function(){
	var dataString = $(this).serialize();
	
	$.ajax({
		url: 'process.php',
		data: dataString,
		type: 'POST',
		success: function(data){
			//Do something
		}
	});
});

The above code waits for the form with a class of '.myform' to be submitted, and then sends the data in the form via a POST method to 'process.php'. If the whole thing works well the success function is called and accepts some data. You would simply set up process.php to either return an error or simply say 'success', and then act accordingly - perhaps showing a success balloon or error notification.

5) Using delegate()

Most beginners typically start by using syntax such as:

$('.myelement').click(function(){
	//Do something
});

Just as I did above. There isn't anything technically wrong with that code, it's just that it could be better. Newbies will often find them googeling why their click() method doesn't work on dynamically created elements (as could be done using AJAX), and the reason for this is because jQuery binds the event handlers to the elements when the page is loaded. So we have to change the way we write our code to ensure we don't run into any issues.

To do that we can use the handy delegate() method. For example:

$('.myWrapper').delegate('p', 'hover', function(){
	$(this).doSomething();
});

The code above tells jQuery to listen for hover events on paragraph elements within the .wrapper element. The method allows us to add elements without worrying if event handlers will listen out for changes to them, and so it is good practise to use it in production.

6) Using powerful selectors

Complex selectors in jQuery allow us to tailor more specific and targeted interactions on our websites. Say for instance we want to target all paragraphs, except those with a class of 'not-me'. A great way to do this is like so:

$('p:not(.not-me)').click(function(){
	$(this).doSomething();
});

There we used the :not() syntax to exclude elements with a class of '.not-me' - a simple, but very effective way of selecting only the elements we want. Furthermore we may only wish to select the first paragraph on our page, to do that we would use another handy selector:

$('p:first').click(function(){
	$(this).doSomething();
});

There are a bunch of powerful selectors besides just class and ID based ones, you can take a look in the docs over at: http://api.jquery.com/category/selectors/

7) Use callback functions

I often answer questions from people who want to know how they can trigger actions once other actions have finished execution. And the simple answer is by using callbacks. For those new to jQuery the term by be unfamiliar, but you've already witnessed one in the AJAX example above! A callback method is one that is called after the method in question has done it wants to do, in jQuery a lot of functions allow you to pass a callback function of your own; let's take a look at how we'd do this:

$('.myelement').click(function(){
	$(this).fadeOut(500, function(){
		alert('Element faded out!');
	});
});

The code above listens for a click on our elements, fades it out, and then alerts the user about it. The callback function is passed as a separate parameter to our fadeOut() method, and is executed after the element is faded-out.

8 ) Use a context

In the interests of performance let's take a moment to think about how jQuery finds elements. When you say something like:

$('.myelement').click(function(){  });

jQuery searches the entire DOM for it. But what if you only have things with that class within say a div with a class of '.main-content'? If so you can provide a context to jQuery (much like we did with the delegate() method above). Doing this enables jQuery to only search within that context, thus saving on performance. And here's how it would look:

var context = $('.main-content');

$('.myelement', context).click(function(){
	$(this).doSomething();
});

The more specific (and smaller) your context, the faster your code.

9) Pass objects not identifiers

When writing your own functions it might seem like a good idea to do something like:

function myfunction(id){
	$(id).doSomething();
}

myFunction(“.myElement");

But that really isn't very flexible. It's far better to actually pass the object around like so:

function myfunction(el){
	el.doSomething();
}

myFunction($(“.myElement"));

10) Don't depend on jQuery

While the techniques above are good advice for writing solid jQuery, you certainly shouldn't depend on the thing. Never use jQuery as a replacement for CSS - not only is it more inefficient, but you are ignoring users without Javascript turned on, and it's a sure fire way to annoy users.

Spice up your Hyperlinks!

Now the words 'hyperlink' and 'sexy' rarely frequent the same sentence in my household, but something which appears to have come into fashion lately (namely I'm using it ;)) is the fading in of the hover state on hyperlinks. So instead of simply specifying the :hover state in your CSS, you use JavaScript or CSS3 to spice up the whole hovering thing. Here's what we will be creating, now lets see how we might go about doing it.

First off let's take a look at the CSS3 way - apparently all the cool kids are using it. If we had a link which we wanted to 'sexify' we might do something like:

.spice {
	color:blue;	
	transition: all .2s linear;
        -o-transition: all .2s linear;
        -moz-transition: all .2s linear;
        -webkit-transition: all .2s linear;
}

	.spice:hover {
		color: red;
	}

Bam! Right there we have one sexy hyperlink using only one CSS3 transition. So when we hover over a link with the class of 'spice' we should see it fade to a lovely bright red, and then upon mousing out, back to that delicious blue. But what happens if (God forbid) a user visits in IE8 or something?! We have support for Opera, Firefox, Chrome and Safari, but not IE. Well surprise surprise we need to have a fall-back for older browsers. And for that, we will be using jQuery (other JavaScript frameworks are available).

Before we continue I should add that I would always suggest using the CSS3 way over the jQuery method, but in any case this is how we do it:

$(function(){
	var color = '';
	
	$('.spice-jq').hover(function(){
		color = $(this).css('color');
		$(this).animate({'color':'red'},200);
	}, function(){
		$(this).animate({'color':color},200);
	})
});    		

Above we first wait for the DOM to be finished loading, and then create ourselves a variable called 'color' to hold the value of the link's colour in it's normal state (if all your links are the same colour, you can just replace every occurrence of 'color' with whatever colour you want). We then animate the colour of the link back and fourth using the hover() function. But before you wonder why the code above doesn't work on your site, I should add that for colour animations, the jQuery Color Plugin is required - so go ahead and include that in your page before the above script.

So now we could using something like Modernizr to detect if the user's browser has CSS3 transitions support, and if not, whack the above jQuery code onto our page. And with that, you should now have a set of beautiful links on your site that make it that little bit slicker.

Building a Confirmation Dialog in JavaScript

Note: This article has been marked for a quality review and will soon be updated.

A common feature of desktop applications is that when a user prompts a potentially destructive action, the program will display a confirmation dialog to ensure that the user doesn't go and do something silly. To do this we will use some basic JavaScript. In this tutorial I will be using jQuery to display and manipulate our elements, but this technique uses good old' JavaScript to get the job done. So let's get started. Click here to see the finished product.

Thee are a few ways to do this, namely we could create a global variable and wait for it to be changed by our dialog function and then proceed; or we could have our function return either true or false based on the user input, and then carry on. However the method we will be using will be to mole net a function that accepts a callback function as one of its parameters. If the user confirms the action the callback function will be called, and of not we will simply hide our dialog and do nothing. So with that in mind, lets create the HTML for our dialog. Here's what I've got:

<span class="lightswitch" style="display:none">
<div class="confirm" style="display:none">
	<div class="wrapper">
		<h3>Are you sure?
		<p>This will clear all the changes you have made.

<button class="left" id="confirm-continue">Continue <button class="right" id="confirm-cancel">Cancel </div> </div>

So we have 2 elements to worry about here - the .lightswitch span, and our .confirm div. The light-switch code will be used to dim the rest of the screen while the dialog is open to ensure focus is directed to whatever we want to put on our pop-up. All that's left is to style our dialog - feel free to go mad with your CSS at this point, but this is what I ended up with:

.right { float:right; }
.left { float: left; }

.confirm {
	display: block;
	width:350px;
	left:50%;
	top:50%;
	margin-top:-100px;
	margin-left:-175px;
	z-index: 1500;
	overflow: hidden;
	cursor: default;
	position: fixed;
	background: #fff;
	border-radius: 5px;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
}

	.confirm .wrapper {
		padding-bottom:10px;
		overflow: hidden;
		font-family: sans-serif;
		color: #000;
	}

	.confirm span {
		width: 90%;
		margin:0 5%;
		display: block;
	}
	
	.confirm h3 {
		background: #212121;
		font-size: 22px;
		color: #fff;
		width:91%;
		padding:2% 5%;
		margin:0;
		border-radius: 4px 4px 0 0;
		-moz-border-radius: 4px 4px 0 0;
		-webkit-border-radius: 4px 4px 0 0;
	}
	
	.confirm button {
		border:none;
		border-radius: 5px;
		-moz-border-radius: 5px;
		-webkit-border-radius: 5px;
		color: #fff;
		background: #212121;
		padding:5px 10px;
		font-size: 15px;
	}

.lightswitch {
	display: block;
	background: rgba(0,0,0,0.75);
	z-index:1000;
	width:100%;
	height:100%;
	position: absolute;
	top:0;
	left:0;
	position: fixed;
	overflow: hidden;
}

The CSS above gives us a centred box with a dimmed background overlaid on top of the rest of the page. The rest of it is just basic styling that you'll want to change to fit with your own UI.

And now to the JavaScript! Here's how it looks:

function confirmIt(title,text,callback){
	$('body').append('');
	$('.lightswitch').fadeIn(300, function(){
		$('.confirm').fadeIn(100);
	});
	
	$('#confirm-continue').click(callback);
	$('#confirm-cancel').click(function(){ $('h1 span').text('Action Cancelled'); })
	
	$('.confirm button').click(function(){
		$('.confirm').fadeOut(500, function(){
			$('.lightswitch').fadeOut(200, function(){
				$('.confirm, .lightswitch').remove();
			});
		})
	});
}			

Let's go through what it does. On the first line we can see the 3 parameters we pass to the function for the title, text, and callback function for our dialog. If the user confirms the action they initiated the callback function will be called, and if not, the action will be cancelled. The function beings by appending the HTML we wrote earlier to the end of our page and then fades-in our .lightswitch to dim the background; and when that completes it fades in the actual confirmation dialog. That's the first part sorted.

We then have to set up some event handlers - for when the user clicks "Continue" and when they click "Cancel". For our continue button we can simply use the function passed to us to confirm the action was intended. We could leave our cancel button without an event handler, but in our case we will change the content of our main heading to reflect the user's choice. But neither of those lines actually get rid of our dialog, so even if the user confirmed/canceled the action our box would still be visible. So to remove it from the screen we will bind a function to the click events of both buttons. In that function we simply reverse the fading-in of the elements, and then remove them from the DOM to ensure we don't go having multiple elements with the same IDs in the future.

And with that we are finished! We now have a good system in place to ensure our users don't accidentally delete or perform some other destructive action on their data.

5 Amazing jQuery Plugins

Okay, so there are plenty of roundups of great jQuery plugins out there, but I've decided to put together a list of some of my favorite. I've compiled this list because I use most of the plugins on a daily basis, and I have found each and every one of them to be a real help when it comes to creating fancy effects using jQuery. So enjoy!

Hover Intent

So you're trying to create some cool effect that takes place when a user hovers over something, but you don't want to go ahead with that effect unless you know the user expressly wants to hover over that item. You could set up some variables and hope for the best, or you could use this fantastic plugin. Hover Intent is build upon jQuery's native .hover() function, but uses some crafty tricks to make sure that your website is fully aware of the user's hover intentions. Find out more here.

The Anything Slider

Now there are some good sliders out there, but this one is one of the best. It combines simplicity with ease of use, and extensibility. Now only are you not restricted to using only images in your cool effect, you can use text, pictures, links, and any other HTML element! It's also feature packed with the ability to use hash-tags to navigate between slides, and total control over animation and pause time. Find out more here.

Fancybox

Yep, it's a light-box. And a seriously good one at that! The reason I like this plugin so much is because of the customization that's allowed - the list of options just goes on and on, and allows you to change everything to have the content appears to what sort of overlay should be placed on top of the rest of the content. Fancybox is also really easy to use, and looks seriously professional. Find out more here.

The Nivo Slider

Now this is another slider that I adore, for totally different reasons. Put simply, the first time I saw it in action, I was blown away by how cool it looked, and I still am! The Nivo slider uses some really clever coding (which I won't pretend to understand 🙂 ) to apply some amazing effects to images. While it can still function as a simple image fade-in fade-out element, the real magic lies in it's other effects, and I would highly recommend you use it if you get the chance! Find out more here.

Quicksand

This truly is a gem of a plugin - Quicksand is a plugin that allows you to sort items. I know - exciting! But when I say "sorting" I mean it in the sexiest way possible! This fantastic plugin allows you to animate the sorting and ordering of your elements on a web-page, and while this may sound mundane and aimless, I assure you, after taking a peek at the demos on their website, you will be impressed. Find out more here.

And that's it! I hope you found this list interesting, and I really do encourage you to have a play around with all of these plugins, as I'm sure you will come to love them as much as I do! And if you know of any fantastic jQuery plugins, feel free to share them with me in the comments!

Using jQuery’s toggle() function

Note: This article has been marked for a quality review and will soon be updated.

jQuery is packed full of useful features that help you to "write less, do more" as their slogan says. One thing I have found over the years, when working with JavaScript, is the need to know what state an object is in. By that I mean wanting for instance to know whether an information box is open or closed, and then perform an action based upon the answer to that question. Now in the past I would use variables to give me this information, and then alter their values based upon the actions taken by the user. This method is somewhat cumbersome and I don't particularly like using it because it takes up quite a few lines of code. So where am I going with this? Well the other day I stumbled upon an incredibly useful function that is part of the jQuery library. And that function is the toggle() function.

The function allows you to set a number of actions that you would like to be cycled through and turns them in to a loop, essentially toggling the action taken. The first time the element is toggled, the first function specified is executed; the second time sees the second function executed, and so on. So, in my case, I was able to simply place some actions within the function and step back from all the complex JavaScript stuff. Let me show you what I mean.

$("#button").toggle(
  function(){
    $("#popup").fadeIn(250);
  },
  function(){
    $("#popup").fadeOut(250);
  }
);

The code above waits for the element named "button" to be clicked, and then fades-in an element named "popup" (I think you can see where this is going :)). You can also use the function as a way of hiding and showing elements in turn, using code similar to the block below.

$("#button").click(function() {
  $(".box").toggle();
})

The code above waits for the element named "button" to be clicked and then shows/hides all elements with a class of ".box" in turn. Remember that you need to set all the boxes you don't want showing to begin with, to have a display value of none.

And that's the toggle() function. It's really simple and easy to use, and it has saved me a lot of time. I thought I better share it with you because it isn't the best known function in the jQuery library, and it is one of the most useful! For more information on the function and some demos of it's usage, visit the API.

Get going with jQuery!

If you would have asked me 6 month ago what I thought of Javascript, I would have told you I thought it was a precarious language which never worked for me - and that's coming from a semi-programmer! To me the language was cumbersome and seemed like it was cobbled together in a very short time with little regard for the developers (don't shoot me!) . For me I didn't have the time to sit down and trawl through documentation on how to use it, and the idea of writing 100s of lines of code for little gain didn't appeal to me.

However a short time ago I was introduced to jQuery - a Javascript library, and I must say it was one of the best gifts I have ever received. jQuery replaces the annoying syntax of Javascript and introduces an easy to use set of tools that can be implemented by someone with little programming experience. Gone are the days when I spend hours trawling over Javascript code to find errors - now I can reel off 50 lines of jQuery without ever making a mistake! Furthermore it's ease of use means that there are loads of websites advocating it. It is free to download - just search for jQuery, and as I say - easy to use.

jQuery allows you to easily animate elements in a slick and stylish manner - making your websites look far smoother. Integration with AJAX means that form validation is also really easy, and best of all - the documentation is amazing!

So what does it look like?

$("#myDiv")

Would select a div element. Then to manipulate it and say fade it in, you would simply add -

$("#myDiv").fadeIn(1000)

The "1000" indicates the length of the animation - in milliseconds. You can even animate individual CSS properties like so -

$("#myDiv").animate({ background-color:"#000"; }, 2500)

And to react to events use functions such as -

$("body").on('click', '#myDiv', function(){ $("#myDiv").animate({ top:"50px"; }, 2500) });

jQuery is a really simple library to learn your way around, and I would recommend going with it because of it's ease of use alongside the powerful features that it possess! If you have never tried jQuery I would seriously suggest you do; I remember when I first discovered it, I spent about a week just playing around with it animating red squares and other random elements, and I think you should do the same - eventually integrating it into a site of your own!