Capturing the URL anchor with jQuery & flashing an element

Today were going to be doing a jQuery tutorial. I was searching a way to animate an element, as if to flash it on and off. But, I didn’t want this to happen on every single page load, just when a certain link was clicked from the home page.

What to do

The easiest way was to capture something from the link that was clicked. Maybe a cookie, or the URL it’s self? I decided to add an anchor of “#like” to the link. Now all I had to do was do something if, and only if the anchor was present.

How to capture the anchor

I went searching for, and found the URL plugin for jQuery which allowed me to do just that. Find elements in the URL.

A jQuery plugin to parse urls and provides easy access to information within them, such as the protocol, host, port, the segments that make up the path and the various query string values.

To do so we need to capture the variable:

var anchor = jQuery.url.attr('anchor');

This is setting the variable anchor to capture any anchor that may or may not be attached to the URL.

Then will use an if statement:

if (anchor == 'like') {
    //do something
}

The above states that if the anchor of the current site’s URL is #like, do something. Be sure to omit the pound key

What are we going to do?

Well, I’m glad you asked, or I implied. If you came to this post from the home page after clicking Likes: (x) then you may have noticed the like this field flash yellow on the left sidebar. If not, you can try it now?

Well I’m capturing the #like anchor and animating the opacity of said element which has a background color of yellow. Lets check out that code:

$j('<span class="like-flash"><br /></span>')
	.insertAfter( $j('.iLikeThis .counter') )
	.fadeIn('normal').fadeOut('normal')
	.fadeIn('normal').fadeOut('normal')
	.fadeIn('normal').fadeOut('normal')
	.fadeIn('normal').fadeOut('normal')
	.fadeIn('normal')
	.fadeOut(3000, function() {
		$j(this).remove();
	});

Can you figure out what’s happening? We’re just creating an element with a class, inserting it after a particular element* and fading it in and out a few times. *You don’t have to add it after a certain element, you can add it where ever you like 🙂

That’s it, lets see the whole code now:

var anchor = jQuery.url.attr('anchor');
//console.log(url); //to see what the anchor is (checking purposes)
if (anchor == 'like') {
	$j('<span class="like-flash"><br /></span>')
		.insertAfter( $j('.iLikeThis .counter') )
		.fadeIn('normal').fadeOut('normal')
		.fadeIn('normal').fadeOut('normal')
		.fadeIn('normal').fadeOut('normal')
		.fadeIn('normal').fadeOut('normal')
		.fadeIn('normal')
		.fadeOut(3000, function() {
			$j(this).remove();
		});
}