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:

	var scrollA = $('body').scrollTop();
		if(scrollA == $('body').scrollTop()){
	}, 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/

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:

	//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:


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:

	var el = $(this);	

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:


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


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:

	var dataString = $(this).serialize();
		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:

	//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(){

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:


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:


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:

	$(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(){

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){


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

function myfunction(el){


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.

Force JS replace to work on all occurrences of needle

When manipulating strings in JavaScript a useful method to know about is the replace() method. It take 2 parameters - the needle and the haystack. So if you wanted to replace 'cat' with 'dog' it might look something like this:

var myString = "The cat jumped over the fence";
var myNewString = myString.replace("cat","dog");

Great it worked. You can also use regular expressions for the needle if you're into that kind of thing - say for instance, if you want to generate a valid URL. It when doing just that, that I realised I had a problem on my hands. My code used 2 replace methods - one for removing special characters, the other to remove spaces. The first was a regular expression, while the second was a basic method searching for a space and replacing it with a dash. My problem was that it was only replacing the first space. And so I had to reach for a regular expression to help me out.

Don't worry if you're not too great with RegEx, this one is really basic, and here's what it looks like:

var myString = "The cat jumped over the fence to meet another cat."
var myNewString = myString.replace(/cat+/g,'dog');

That bit of code tells the rendering engine that we are using a RegEx with our forward slashes, inside we have the word we are looking to replace, then the plus symbol tells it to match the preceding word (in our case 'cat'), 1 or more times. Then the magic happens - we use the 'g' character to tell it to look for all occurrences.

And that is how you ensure all occurrences of a needle are replaced when using the replace() method. Hopefully this article will save you scratching your head over why a seemingly obviously method won't play ball.

Adding subtle user feedback

We all hate waiting for websites to load right? It's annoying to watch images download and wait for Twitter streams to render isn't it? Well it's a fact that 99% of websites have this issue - that is, that load time is about 1 or 2 seconds. Now for companies like Google it isn't an issue, they have enough money to ensure they have sites that load instantly; but for us average folk what can we do? Investing in new and expensive serves often isn't an option, so one method I propose is creating subtle user feedback.

One way to accomplish this is to go all AJAX, instead of letting the browser jump between pages, simply load they pages using Javascript and fade in a loading animation while you do just that. Great, problem solved. Or is it? What about large sites that are already up and running? Is it a good idea to re-write a lot of code? Well while AJAX will provide you with the most control over UX, I propose a slightly different method, details of which follow.

I recently finished work on a site which has a load time of about 1 second - pretty average stuff. But I wasn't happy with just providing the normal experience. I thought about fading/sliding in individual elements when the page had fully loaded (much like Apple now does on it's product pages. But the problem with that is, if done incorrectly, you end up extending the load time of a site, and no matter how nice an effect might look, if it harms the end user-experience, it's best to leave it out (at this point I should say that if you load a page and then send multiple requests for more data, and then fade them in, that makes sense). So I came up with a simple solution - add a loading header graphic. Allow me to elaborate.

Instead of simply loading a page with the normal logo of the site in the header, I load a GIF that looks exactly like the header graphic (minus the text), and once the page has finished loading (courtesy of jQuery), I swap the images out. So what does it look like? Head over to Cooking Pete (shameless plug I know) to see the effect in action.

I used the:

$(document).ready(function(){  });

Function to allow me to detect the fully loaded DOM, and then simply change the src attribute of my header graphic.

And that's it! Adding simple user feedback like that let's your users know that the site is doing something, and doesn't leave them in the dark.

Adding Vignettes to Images with CSS

Vignettes are something we've been able to add to images in Photoshop for many years - it describes the technique of reducing clarity towards the edges of images by reducing things like saturation and brightness, and can often give an image a different quality. It was for that reason that I decided I wanted to use them in my designs, but I certainly didn't want to use images that were pre-composed with the effect, and so decided it would be simple to add them using CSS. What I didn't know, was that there were many things conspiring to prevent me achieving the effect properly. So without further adieu, allow me to share my experience with you.

I first read Trent Walton's article on vignetting and implemented that on the site, but soon realised its shortcomings. Firstly the use of negative z-indexing played havoc with my backgrounds - this is because its fine if you have an all-white background, but if you have an image, it simply throws the picture behind it. And secondly I found myself frustrated with the fact that you couldn't right click and save the image with ease. I also took a look at Chris Coyier's article on the subject, but once again hit a brick wall.

So after a lot of playing around and many alterations I came up with a solution that is the combination of many techniques that I have come across, and the one use on the site today.

My HTML is as follows.

    <img src="path/to/image" alt="Test image" />

The class of left simply floats the element to the left, while I use the following CSS to style the rest.

figure {
	position: relative;
	display: block; 

	figure.vignette img {
		z-index: 1;
		position: relative;
		display: block;

	figure::before {
		content: "";
		position: absolute;
		top: -1em;
		bottom: -1em;
		left: -1em;
		right: -1em;

	figure.vignette::after {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		content: "";
		z-index: 2;
		pointer-events: none;
		box-shadow:inset 0px 0px 85px rgba(0,0,0,.5);
		-webkit-box-shadow:inset 0px 0px 85px rgba(0,0,0,.5);
		-moz-box-shadow:inset 0px 0px 85px rgba(0,0,0,.5);
		border-radius: 3px;
		-moz-border-radius: 3px;
		-webkit-border-radius: 3px;

So the main styling of the figure element simply makes sure it is visible and sets it's position to relative, as does the styling of the image within it; but it is the code that follows that does all the magic. We use the pseudo ::before and ::after to apply the vignette effect. If you are unfamiliar with those selectors, visit W3's article on the subject. You can increase the intensity of the vignette by altering the box-shadow property to have a less transparent shadow, or bigger radius. You could even have different colours by altering the same property.

And that's it! I haven't found any inherent problems with this technique just yet, and although this method isn't really apply a vignette in the traditional sense, I feel it does a pretty good imitation of it.

QuickTip: Create a dotted/dashed line in Photoshop

More and more often nowadays I am finding the need to create dotted or dashed lines in my Photoshop mockups, but what is a ten second job in CSS, could turn out to be a ten minute job in Photoshop if you don't know how to do so easily. Before I came across the trick I'm going to show you today I would do one of two things. Either just make it solid in the design and say to myself - "that there is a dotted line", or being the perfectionist that I am, go around drawing a line, and then using the marquee tool to delete every second pixel - I know crazy right?! But then I had a brainwave, why not just use the brush tool? I was working with creating some funky brush strokes when i hit me, and so now I am able to create a dotted/dashed line in seconds in Photoshop, here's how.

To begin select the brush tool, and open up the brush window as seen below.

Then select the width of the brish you would like to use, in this example I selected the 1px round brush. If you would like a dashed line this is the point at which to select a square brush, also if you are wanting a dashed line you will need to alter the "roundness" of the square - bare with me here. Simply reduce the roundness value until you have your desired width, as you can see below.

To reduce the size simply select the preset you require. Now make sure the spacing checkbox is check and use the slider to increase the spacing dramatically, like so.

Then head over to your canvas, select a colour and hold down shift while you click and drag to create your line. Holding down shift will ensure you create a straight line. Now if you want to create a dotted or dahsed line, but you don't want this line to be straight, you will need to follow a few extra steps. They are as follows. Firstly gray the pen tool and draw the shape which you want the line to follow, like so.

Then right click the path and select "Stroke Path...".

From the Tool menu in the dialog that presents itself, select "Brush".

And then you should have successfully managed to stroke your path and created a dotted line like so.

And that's it! This technique is really simple and creates really nice results, and best of all, only takes a few seconds to achieve. I hope that this method will save you a good amount of time in the future when trying to design a website in Photoshop to look exactly as it will in the browser. Now if only I could create stunning designs as easily...

Using absolute and relative positioning

Now to many people this might be a really simple concept, that is the concept of using absolute and relative positioning; but I remember when I started web design I wasn't really sure what either meant. So this article is aimed at explaining why you might want to use the two properties in conjunction with one another, to have more control over how your site looks. So we'll start with absolute positioning.

When you set an element's position property to "absolute" you are telling the browser that no matter what configuration (browser size/resolution), you want that element to be in the same place. You also take that element out of the flow so that it doesn't affect any other element on the page. So as an example if you set an element's position to absolute, you can then say how far from the top, bottom, left, or right you want to to be - relative to the browser window. So...

#element {

Would send your element to the top-right of the browser window.

Why would you want to do this? Well little example here - my canvas example from a few posts ago, positions the options panel in the top right-hand corner of the screen. Why? Because I want it out of the way, but always available. This style of positioning is interesting because it means you can ensure how an element will look. Maybe you want an ad in the bottom left. Perhaps you want a feedback link always on the left? Or maybe you just want better control of comment meta data. And that's a great example. Many sites use absolute positioning to position things such as meta data with other elements as to make sure they don't move a pixel out of line.

But how would one go about doing that, if absolute positing is relative only to the browser window? I hear you ask. Well, this is the part where I introduce you to our little friend, relative positioning.

Now in nearly every tutorial about positioning, when they get to the subject of relative positioning they usually say something along the lines of "it will make the element's position relative to itself" - but what on Earth does that mean?! Basically you are able to offset the element relative to where it would have been. So if one element was supposed to be at the coordinates (200,100) and you set it's position to relative and top:50px; right:20px, it will now lye at (250,120). All very well and good. But how does this relate to absolute positioning? Well here's where it gets interesting - if you have a container which is positioned relatively, and an element inside of that container positioned absolutely, then the element will be positioned relative to the size of the container. See below.

So that's about it. A combination of these two types of positioning can be really useful - I use it all the time for styling the sometimes tricky comments section of WordPress themes and there are a million other applications for the wonderful CSS property - and remember with great power, comes great cross-browser-compatibility 😉

Why jellybeans? Because it would be a heck of a job positioning them (oh and they look nice :)).

Playing with the New Canvas Element

Full adoption of HTML5 is just round the corner, and with more and more browser-vendors making HTML5 top-priority these days, it's time, I think, we should take a look at some of the cool things we can do with the new <canvas> element. So what is it? Well although I don't profess to be an expert, I should tell you that it is much like a canvas in the real world, in that you can draw on to it using code, you can stick pictures on to it, and more interestingly you can manipulate these pictures. But a wonderful aspect of the new element is that it isn't really that hard to get to grips with, and the code for creating some interesting stuff is relatively simple to learn. So instead of writing a load of uninteresting and complex code out, I thought I might just tell you of a very simple idea that I, like many others, had.

After playing with the element for a short while I suddenly realised what I could do - make a really simple drawing application! I know not the most far out or original idea, but I liked the idea. So I set about creating it. Here's the demo. So as you can see it is really simple, but you might think that there would be a lot of code to create it. Actually the code that listens for the mouse click and drag actually occupies more space than that of the canvas code. Let's have a look. Here is the HTML.

<div id="controls">
<input id="brushRadius" type="text" value="4"></input>
<input id="brushColour" type="text" value="000000"></input>
<div id="palette"></div>

<canvas id="blank">
Your browser doesn't support this feature.

So at the top you can see the controls section, which allows the user to input two variables - the stroke width and the colour - both very simple. Below this is a small box which will have it's background colour set to that of the current brush colour later on. Now the Javascript. Notice the text between the canvas tags, this will be displayed if the browser doesn't support the canvas element.

var canvas = document.getElementById('blank');
var ctx = canvas.getContext('2d');

ctx.lineWidth = 4;
var mousedown = false;	
	mousedown = true;						
	mousedown = false;	
	var x = e.pageX;
	var y = e.pageY;
	}else {		
	ctx.lineWidth = $("#brushRadius").val();
function updateColour(){				
	var colour = $("#brushColour").val();

	ctx.strokeStyle = "#" + colour;
	$("#palette").css("backgroundColor","#" + colour);					
$("#brushColour").change(function(){ updateColour(); });
$("#brushColour").keydown(function(){ updateColour(); });

Right, it may look like a lot, but bear with me. At the top we declare the canvas and make it into a 2D area to draw onto, we also declare a variable called "ctx" (short for context) to hold the canvas element, thus making the code more efficient. Then we set the canvas to fill the entire window and make a variable called "mousedown" and set it to false, notice we also set the brush width to 4 as a default value. This will be altered whenever the user clicks and hold the mouse button down by the following functions. Next we use the mousemove function to detect movement, and check to see if the mouse button is down. If it is then we draw a line from the previous location, to the current location and stroke it, otherwise we simply move it.

After this we listen for the #brushRadius input to be changed and then alter the line's width based upon the value inputted. The reason we close and then open the line, is to stop the changes affecting the previously drawn lines. Finally we have a function to update the colour. This function makes a variable to store the inputted value, closes the line, updates the line's colour, and then starts it again. And then it updates that box I told you about earlier, to reflect the inputted value. This function is then executed using the following two functions that fire whenever the input is altered.

So there is a lot to take in there, but after you familiarise yourself with it, you should begin to understand the simplicity of the code. The canvas element can do so much more than what I've shown you here today, and I would encourage you to get to grips with it. I would suggest a trip to the Mozilla developer's centre and go through the tutorial. It really is nice to have such power reasserted using such simple code - enjoy!

Element Organization

So what do I mean when I say element organisation? Well put simply I'm referring to the way in which we group HTML elements in terms of either tables, divs or HTML5. Now to be honest I believe that tables these days are somewhat obsolete and I wouldn't even bother teaching it to new web designers so the objective of this article is to show you that you don't need tables! Let's begin with the trusty <div> element. We're just going to create a nice layout that could perhaps replace a table! (Just bear in mind that this is a rather basic tutorial).

Dividing, or div, elements are really easy to understand and once you get using them, you won't ever go back! So lets create a simple page header using div elements.

<div id="header">
  <h1>My Website</h1>
  <div class="nav">

So there we have some code that will create our header, for the moment lets just focus on the <div> elements. So you'll see that we create these elements by using the standard convention of the less than and greater than symbols and then entering the word "div" which just tells the browser that it is a dividing element. We then have a few parameters that we can set. First off we can give the element an ID which we can later reference in our CSS or JavaScript, so you would only give and ID to something like a header or a main content box (basically just a name that isn't going to get used again). Then we can give it a class which we can use over again and acts much like and ID. Lastly we can actually apply styling to individual divs, e.g. <div style="display:none"><div>. This comes in handy when we want to show and hide elements on the fly, but you should know that in-line styling isn't something I advocate.

Lastly you will notice that we end our element with <div>. Now in the code above you'll notice that we have some elements in between the opening of the div and the closing of it. This is because the whole point of a div to to group elements together so that you can manipulate them later. However you can have an empty div that you can apply styling to if that's something you're interested in doing.

At this point in time I only create with divs, however in the near future it will soon become the norm to use HTML5 to group your elements. Now you can already do this, just as long as you are aware that it isn't yet fully supported. But for when that time comes you should have an idea on how you might style the same sort of code with HTML5. Now I'm not going to cover the in-depth areas of HTML5 just so as to stick to the topic in hand. So here is the code that would replicate the stuff you see above, but in HTML5.

  <h1>My Website</h1>

Now what you will notice about this is that it looks slightly cleaner and somewhat resembles XML, you'll see that in HTML5 many of the most commonly used names for divs have just been turned into actual tags; something which I'm sure I'll come to love.

And that's it for that little segment. To finish I'd like to go over another basic topic regarding using IDs and Classes when naming your elements. First IDs.

An ID, or identification, is used when we want to reference a singular element on our page; it is a name that can be used only once and can be added to elements like so - id="myElement" - that was easy wasn't it? Now when we want to actually reference an element with an ID in either CSS or JavaScript/jQuery we have to use the hash (or pound) symbol - # - e.g. #myElement { display:none; } in CSS and $("#myElement").hide(); in jQuery. So you give IDs to elements such as the header and main content box so that you can group a number of other elements and apply certain styling to them all.

Next classes. These are used to "class" elements together and more importantly can be used as many times as you like! They can be added to elements like so - class="left" - and you should know that you can add multiple classes to singular elements like so - class="left hidden". This is really useful when you want to have styling that you can apply to whatever elements you might need to, for example you might want to float all elements with a class of "left" to the left. But you might also want to hide some elements using the "hidden" class, I think you can properly see just how useful this can be. Now when you want to manipulate elements with certain classes we simple have to use a full stop (or period), e.g. .left { float:left; } in CSS and - $(".hidden").hide(); - in jQuery.

So I hope this article goes some way towards the eradication of table-based layouts on the web, and I hope you found it useful as a reference about IDs, Classes and divs!

Replacing the […] in WordPress

Some of you might be wondering what I mean by the [...], well I am of course referring to the symbol generated by WordPress upon calling the function the_excerpt(). Now personally I really dislike the symbol which is generated as it often doesn't fit with my design, and I always prefer to have an ellipse - ... followed by a link to continue reading - but how on earth could we go about doing this? Does the answer lie in using jQuery to find and replace this horrendous symbol? Perhaps we need to add some arguments to the the_excerpt() function?

No, it's far simpler than that.

All that needs to be done is the addition of some code to the functions.php file in your theme directory. So head over to this file (if it doesn't exist, create it) and go to your next free line, and copy and paste the code from below.

function new_excerpt_more($post) {
	return '...</p><a href="'. get_permalink($post->ID) . '">' . 'Continue Reading...' . '</a>';
add_filter('excerpt_more', 'new_excerpt_more');

So the above code replaces the default [...] with something that looks like "... Continue Reading...", where the continue reading text is a link to the article itself. You could replace this with whatever code you like and have bundles of fun if you like that kind of thing. Just remember to not leave any blank lines at the bottom of your functions.php file as this can cause errors later down the line.