Specific URL welcomes with jQuery

07/07/09 :: Posted by Rob

So my good twitter friend @tomsturge had an idea that when people came onto his site from a certain place that they would get a small welcome message.

His idea was to have his link with a specific # at the end, in his case #twitter, that when people entered his site via that URL it would trigger a small welcome box.

He asked me for some help as of how to do this with jQuery, although I am by no means a jQuery master, after a bit of thought it all came together.

The tutorial probably wont be the best and most efficient way to create something, but I wanted to show you how easy jQuery can be to get into.

To avoid boring most, but enabling others who are less advanced to learn please click the toggle details button if you are more advanced than beginner with jQuery.

Click here to Hide/Show the extra beginner details.

Example here

Overview: To create a small box with custom content that will pop up when the site is entered through a specific hashed (#) URL.

We need to link in the jQuery library.  You can do this by either linking to it to the website or you can download it from here and host it somewhere on your server, or using this code between your head tags, after your CSS.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"><!--mce:0--></script>

Next you can create a *.js file and link as you have the jQuery library.

<script src="yourcode.js" type="text/javascript"><!--mce:1--></script>

Ok so now you need to start the jQuery. Add this to the new *.js file you created.

$(function() {
 
});

All your code will be put inside this function, all it does is declare that when the document is ready it will run.  Its standard to use this for starting all jQuery, its also shorthand for a the same function you may see in other tutorials.

So onwards to the code.

The best way to create your jQuery is to think through the problem logically.

User clicks the link and enters your site; a box pops up and welcomes them if they have come through a specific URL.

We need some way of jQuery to log what URL they have come through and save it in a variable.  Next we need to create a box that will be visible when that URL is used, and then we need a way of closing the box.

As you can see, this sounds simple, and the great thing about it – it is!

Firstly we need to figure out what the URL is for the current page.  We can do this by using the “window.location” JavaScript location object.  We will need to store the result in a variable so that it can be called back.  We can do this like so.

var twit = window.location;

This will store the URL within the variable “twit” for you to use when needed.  If you like you can do a little test to see if the variable is working by using the console logging option.

var twit = window.location;
console.log(twit);

To see the result you are best of using Firebug, and check the console window after the page has loaded.

Next we need to set up a very simple if else statement.

We want the script to run if the variable is the same as the specified URL.

if (twit == "http://www.myURL.com/#hastag") {
 
} else {
 
}

You can see between the brackets we have placed the VARIBALE then a double equals symbol.  After that you can put in what you want the variable to match, which will be the desired URL, and you store it as a string within “ “.

If the VARIABLE is exactly the same as the string (which is what == means), it will run the following script which is placed in curly brackets.

if (twit == twit) {
 
	$("<div id='popbg' />").appendTo("#wrap").animate({opacity: 0.8}, 300); 
	$("<div id='pop'><a id='closepop'></a><p>Welcome!</p><p><a href='http://twitter.com/svgrob'>Click for Rob</a></p></div>").appendTo("#wrap").css({left: boxmid}).animate({opacity: 1.0, top: +30}, 600);
 
 
} else {
 
	$("#pop").remove();
 
}

This script builds us 2 divs and places it in the document. The first is to darken the background, in the traditional lightbox style. We use CSS to style this box attractively :) :

#popbg {
width:100%;
height:100%;
background:black;
position:absolute;
}
 
#pop {
background:green;
width:600px;
height:400px;
position:absolute;
color:white;
font-size:4em;
text-align:center;
}

Using a standard HTML element creates it, then we are able to append it to the #wrap class – this could be whatever our page wrap, body or html tag.  I prefer it on the page wrap, we just have to make sure it is right a the end of the document (which is what append does), then we dont have to worry about z-index too much. I also added a little bit of content in there too – a closepop link, some text saying “Welcome” and a link to my twitter page, you can put in whatever you want, I just added that as a syntax guid :)

Then in the Else statement we have a very simple selection of the box that and a remove.  You don’t really need this here, but I thought if it by chance was a little buggy it would kill it off… no excuses then.

You could even add another box to appear if it isn’t the URL specified and give a different welcome message, or whatever it is you are displaying, just put that script in the else :)

Ok so at this point you might realise our pop up is not displaying in the centre of the page.  There are probably a few ways we could make this work, but I want to show a way that will give you some simple maths examples and will teach you a little about mixing variables up to get the result you want.

First we need to find the width of your browser window, you can do this by targeting the html tag and then using .width().  This will return a numerical value of the px width of your html tag, which unless you have specified a width in the CSS will be the fill width of your browser window.  So you need to assign this to a variable so you can use the value.

var width = $("html").width();

Now we need to half that variable value so we can get the centre of the document. We can do this by dividing the previous variable by 2, like this.

var centpoint = width / 2;

So now we know that this variable holds the value for half of the width of the page.  If we set the box to pop up appear with this variable it will be too far over, as the boxes left edge will start at the centre point, we don’t want this.

So to get around that we need to pop the box value in to a variable, the box in this tutorial is 600px wide, so we can set the variable at the top of the script under the window location like this:

var twit = window.location;
var boxwidth = 600;

Also if we set it at the top we can easily change it if we need to. This keep future adaptation of the script easy to do.

Now we can take this variable and / 2 to get half its value.

var boxhalf = boxwidth / 2;

Once we have half its value we can then take away that variable from the centre page variable, this will take away half of the box from the centre point, leaving the box centred!  Genius.

var boxmid = centpoint - boxhalf;

So to centre our box relative to the browser window size, the variables should look something like this:

var boxwidth = 600;
 
var width = $("html").width();
var centpoint = width / 2;
var boxhalf = boxwidth / 2;
var boxmid = centpoint - boxhalf;

Its important to get you head around the power that is in variables, as you can see the above is completely flexible, if say your user loads the browser not at their full screen or whatever resolution they are using the width() will always return the actual width of your HTML tag at the time the page was loaded.  The variables are then able to work this data into the answer you need.

Ok so we now have our box pop up, but now it wont go away, so we need to do a little bit more.

We need to create a new function that will “listen” for a click from the users mouse. Now in this example I have created a small link in the pop up box that has an id of “closepop” and styled it like this:

#closepop {
display:block;
height:20px;
width:20px;
position:absolute;
top:-5px;
right:-5px;
background:black;
cursor:pointer;
}

Obviously you can make it pretty…

Now as you can see it just sets a small link displayed as a block in the top right. I would make it a nice “X” close icon button or something.
Here is the code for the click:

	$("#closepop").click(function() {
 
		$("#pop").animate({top: -10, opacity: 0.0}, 600, function() { $("#pop").remove(); });
		$("#popbg").animate({opacity: 0}, 300, function() { $("popbg").remove(); });  
 
	});

As you can see it listens for the click, then excutes the function of removing the background and the box.

To make it a little more interesting I made the box fade out and slide up to reflect what it does when it appears. Each ends in a .remove() that pretty much just deletes the element, so its not even left in your code after the script has finished.

Hopefully you were able to follow all that, remember if some things didnt make sense and you viewed the shorter version, you can always click the details button at the top and run through it again. Now get using jQuery coz its awesome! :)

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Design Float
  • email
  • LinkedIn

Tags: ,

This entry was posted on Tuesday, July 7th, 2009 at 11:57 am and is filed under Tutorial. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

  1. You should use “window.location.hash” rather than the full location string, so your script will run on every page of your site, not only on the homepage.

    ( And your comment textarea is broken, it disappears behind his container )

  2. Grouchy Smurf says: Grouchy SmurfNo Gravatar
  3. Grouchy – thanks for taking the time to read it! I hope it made sense :)

    Yea the comment area needs sorting in Safari for sure – just not had chance to rectify it :D

    Thanks again dude :)

  4. Rob says: RobNo Gravatar
  5. Oh! It’s the much talked about tutorial. Great job! Shame I’m not currently using it for a working in context example, or got a website at the moment for that matter.

    Thanks for the mention at the beginning too =O)

  6. Thomas Sturge says: Thomas SturgeNo Gravatar
  7. getenv(“HTTP_REFERER”);

  8. Hmm says: HmmNo Gravatar