Tutorial: Simple Cross-browser tooltip with CSS

We see tooltip almost everyday on the web. And most of us know there are a lot of way of doing this. Personally, i think the easily way of accomplished this is by using CSS. Although there are disadvantage and advantages of doing this which we will discuss later. Nonetheless, it is one of the most easiest way of accomplished a tooltip. (although the MOST easily way is to just use a title attribute in the tag without any additional code)

The Concept

This method neglect the use of 'title' and apply 'span' tag instead. We know that span tag won't add additional break to a text (which is what we want!) and is usually used to highlight text on a particular paragraph. Therefore, span tag can be used perfectly to substitute title attribute although it cannot totally replace it. So what we do here is by placing the span tag within the anchor tag and style the span tag with a absolute position while the anchor will have relative position. This way, the span tag can have any position away from the anchor tag which provides a tooltip like position. The last missing puzzle will be using an pseudo class to perform a CSS hover on the anchor for displaying and hiding the tooltip. That's it.

The Code

The concept illustrate the basic use of this method. We can further enhance it to cater for more visual effect such as adding additional image on the tooltip.

The HTML

	<a href="#"> Mouse over me to see what i have to say!
	<span class='tooltip'>
	<span class='top'></span>
	<span class='middle'>this is a testing site to demonstrate how simple a tooltip be build without affecting the efficiency of the overall site. Only pure CSS implementation is required. No additional JavaScript is needed actually. Well, unless you want to do something different like dragging your tooltip around a particular images, you may consider using a simple jQuery or JavaScript code to accomplish that.</span>
	<span class='bottom'></span>
	</span>
	</a>

We will have an anchor and inside the anchor we will have two things, the link message and the tooltip. The link message is 'Mouse over me to see what i have to say!' which is quite obvious and the span tag will locate next to it. Actually we only need one span tag if we are doing a simple border tooltip without images but we want to enhance overall look of the tooltip so we need a few nested span within the main span tag as shown above.

The CSS

a {
    position:relative;
    color:#3CA3FF;
    font-weight:bold;
    text-decoration:none;
}
a  span{ display: none; }
a:hover{ 
color: #aaaaff; 
background:;
}
a:hover span.tooltip{
    display:block;
    position:absolute;
    top:0px; left:0;
	padding: 15px 0 0 0;
	width:200px;
	color: #993300;
    text-align: center;
	filter: alpha(opacity:70);
	KHTMLOpacity: 0.70;
	MozOpacity: 0.70;
	opacity: 0.70;
}
a:hover span.top{
	display: block;
	padding: 55px 8px 0;
    background: url(../images/main_image.png) no-repeat top;
}
a:hover span.middle{ 
	display: block;
	padding: 0 8px; 
	background: url(../images/content_image.png) repeat bottom; 
}
a:hover span.bottom{
	display: block;
	padding:3px 8px 40px;
    background: url(../images/main_image.png) no-repeat bottom;
}

I will explain the CSS code above in point form

  • 'a {...': We declare the basic of the anchor tag. eg. color, decoration, bold, position but the key is position relative as stated on the concept section
  • 'a span{...': the tooltip should be hidden at first
  • 'a:hover{...': We need to set the hover z-index and a small hack 'background:;' for ie.
  • 'a:hover span.tooltip{..': this is the tooltip and the declaration of important are 'width', 'position' and 'display'. Width is the size of the image, position is describe on the concept section and display is block because we need to make the tooltip available when hover. Others should be simple to understand
  • 'a:hover span.top{..': the top part of the image to be display
  • 'a:hover span.middle{ ..': the image part where it will be scretched
  • 'a:hover span.bottom{..': the bottom part of the image to be display

The reason why it is 'a:hover span...' for the image declaration was because we want the hover to be maintained when our mouse move on top of the tooltip instead of just having the normal 'mouseover' on the anchor tag which will make our tooltip display whenever our mouse move away from the anchor on top of the tooltip. If you just want a simple tooltip, remove the 'top', 'bottom' and 'middle' from the above declaration and give border to 'tooltip' (you may want to remove the opacity declaration for close browser) which will easily give you a simple tooltip in a few second but the visual part will be lost.

The Advantages

Here are some of the advantages of using this method,

  1. Efficient compare to JavaScript method
  2. Independent. User can turn off JavaScript and it will still work
  3. Quick and dirty. A few lines of CSS and we have our tooltip
  4. No redundency. We will be using CSS even with JavaScript
  5. Etc.

The Disadvantages

Here are some of the disadvantages,

  1. Bad for SEO. search engine spider look at title and also the use of span within an anchor is not a standard practice
  2. Required certain CSS hack for it to work at lower browser (not really a disadvantage but consider as a problem)
  3. The tooltip cannot follow the mouse wherever it goes.(image tooltip)
  4. If this method has a title on it, it will display both the tooltip and the default title altogether. Bad
  5. Etc.

The Demo

Here are the files and demo for simple cross-browser tooltip with CSS

Tutorial: How to make your own simple and nice Slider with jQuery Part 2

In my previous tutorial on how to create a Slider with jQuery, i illustrated the concept to build up an jQuery Slider easily with a few line of jQuery code and an explanation on how it is being done. But in my previous article, it doesn't work as perfectly as this one since our objective is to provide an understanding on how it work. In this article, i will bring out the fully workable version of my previous article. Short to say, this article will contains more information on why the previous one doesn't work as well as what has been found and solved.

Requirement

Before i start this short article (hopefully) there is some requirement that i wish you could follow before proceeding to read further.

  1. Read the previous tutorial on Slider with jQuery because in this article i won't repeat much on the concept and how it is being done!
  2. Have basic knowledge of HTML, jQuery and CSS
  3. Wish to construct a workable jQuery Slider on your own instead of just understanding how it work

The Problem

There are a few things i came across when working on a jQuery Slider from my previous article.

  1. The scroller doesn't stop when the user mouse up sometimes
  2. jQuery doesn't support sequence event trigger: means it cannot prioritize which event should trigger when an element has multiple events
  3. The mouse will always pull to the starting line of the scroller

This is as far as i remember for what happen between the current and the later version differences. Although both work quite well.

The Solution

The CSS and HTML are perfectly the same! The only differences occurred on the jQuery codes and below listed what has been done to eliminate the above issues and the final code in jQuery.

  1. The mouseup event handler was embedded within mousemove event handler. This means that mousemove must first initialize before mouseup will be triggered which is not always the case. Thus, the two event handler were seperated.
  2. Since jQuery doesn't support priority event triggering, i used a boolean variable to stop the movement and wait for mousedown event to complete before it can start the other instruction within the mousemove event. This will solve the problem where mousemove initialize first before the distance between the scroller and starting point being calculated in mousedown event.
  3. The reason why it always pull to the starting line was because it was instructed to do so. I did not calculate the disance between the scroller and starting point which is required to tell the program to start at any point occurs within the scroll bar!

The above explanation might not help you understand a single bit at all! But the below code will definitely assist you in relating the explanation above.

$(function(){
	var myoffset = $('#scroller').offset();
	var myxpos = parseInt(myoffset.left); 
	var width = parseInt($('#scrollbar').css('width')) - 196;
	var action = false;
	var startpos = 0;
	var move = 0;
	var scroller = 0;
	
	$().mousemove(function(e){
		move = parseInt(e.pageX-myxpos);
		$('#scroller').mousedown(function(){	
			action = true;
			scroller = parseInt($('#scroller').offset().left);
			startpos = move - (scroller - myxpos);
		})
		if(action)
		{
			move = move - startpos;
			if(move < = 0)
				move =0;
			if(move >= width)
				move = width;
			if(action)
				$('#scroller').css('left', (move)+'px');
		}
	})
		$('*').mouseup(function(){
			action = false;
		});

});

Let's see how do i explain this. Let's do it in point form similar to the problem we have.

  1. Notice '$('*').mouseup(function(){...' was placed outside instead
  2. Notice 'if(action)......' was there to stop all instruction from initializing before '$('#scroller').mousedown(function(){..' completed'
  3. Notice '$('#scroller').mousedown(function(){ ....' contains variables 'scroller' and 'startpos'

I think this will clear out what my messy explanation has just caused. After these three has placed up, you will have a full and nice version of jQuery Slider from my previous article.

The Demo

It will be pretty confusing whether there is really a full version of jQuery Slider without using a jQuery Plugin. Thus, i have prepare two demo for you. The first one is the understanding demo and the other one is the current full version demo!

Tutorial: How to get image path on a post in WordPress efficiently

This is something that WordPress currently doesn't support yet. You will face the problem of retrieving image on a particular post on the loop while you are working on WordPress theme or plugin. WordPress doesn't provides you with a method that you can use to retrieve the images on the post and you would have to search all over the internet to find someone sharing their secret with you. Thus, rather than using a complex or methods built by others, i personally have a much simple and efficient way of doing this.

The Problem

I wanted to retrieve all images on a particular post under a category and make it into a gallery. However, WordPress doesn't provides such method. Furthermore, the methods provide by others seems to complex this particular function. I want a simple and efficient way of doing this. Not a redundant one.

The Solution

The best way is to look into the core of PHP and search for a particular function that do this automatically. I search quite long and finally found preg_match_all from PHP core build. However, it return the number of match element instead of the result of the URL! But if you read closely it can also retrieve the matched result. So, how do you retrieve the images? Answer is regular expression! What i did was as follow,

$content = get_the_content();
preg_match_all('/src=\"https?:\/\/[\S\w]+\"/i', $content, $matches, PREG_SET_ORDER);
foreach($matches as $e)
{
	echo '<div class="slideshow_box"><img width="106px" '.$e[0].'/></div>';
}

Basically, i retrieve the content using WordPress method 'get_the_content()'. Using the preg_match_all PHP function i placed a regular expression that will retrieve all string that start with 'src="' and end with a single '"' quote symbol. You can read more on regular expression on Google (although until now i still can't find a real good reference). it will return the number of match result normally but with the additional variable, $matches which store all matched string, we can easily get all images on a post in WordPress without building additional big function to do this. You can remove 'src=' to retrieve something like 'www.hungred.com' instead of 'src="www.hungred.com' but if you know regular expression better than i do, this will easily be a piece of cake for you.

The Conclusion

This may seems to be an obvious thing to do. But you may be surprise after doing some Google search that many people actually built up function just to accomplished this and no one is sharing such sweet method with you! This is just to write out to help others who are still searching for a better solution than looking at complex method created by others. Hope it help.

Tutorial: Simple grey out screen effect with jQuery

Grey out screen is done previous in JavaScript. But jQuery has became so powerful in reducing the number of codes required that makes me wanted to try how well this can be done using it. Personally, i wanted to check out how easy it is to create a grey out screen with a pop out box at the center of the screen. This is purely for the sake of exploring and experiencing how simple can a grey out screen be done in jQuery.

The Objective

The objective of this article is to produce a simple grey out screen effect in jQuery with the minimum amount of code required. Of course, this is just the goal. But let's see how simple and easy this can be done with minimum amount of codes and maximum completeness.

The Requirement

Here are the following requirement for this simple tutorial

  • Basic CSS, HTML, jQuery Knowledge
  • Read what is written!

Although it is obvious, but usually people tend to skip the second requirement.

The Concept

Let's imagine the body tag (also known as <body>) is the curtain and the box is the person who will appear when the curtain is closed. If the box is in the body when the curtain is closed, we won't be able to see the box!(you will see no person out on the front when the curtain closed). Furthermore, if we grey out the body tag the background of the page will change to black instead of grey which is not what we want. Therefore, the grey out screen should be placed as a standalone curtain just below the body tag (children of <body>). Normally, we will usually assume when the screen is grey out, all the child within the screen will also be grey out and those that are outside are unaffected. Unfortunately, this is not the case. It may surprise you but any element in the screen will be display instead! eg. anchor or hyperlink. Thus, if you want your element to be untouchable after grey out effect, it is best to placed grey out screen as standalone!

The Code

The code will be split into three part, HTML, CSS and jQuery. There will be more explanation than codes since we will want to understand what is going on in the code and the code is suppose to be MINIMUM

HTML

We will need three things in this article. They are 'box', 'screen' and 'button'.

	<input type='button' value='grey out me!' id='button'/>
	
	<div id='box'>
	</div>
	
	<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
	
	<div id='screen'>
	</div>

And finally a lot of break to make the page long enough to detect a problem later on. The elements are describe below,

  • box: the pop out box after screen grey out
  • button: the button that will initialize screen grey out
  • screen: the screen that will cover the whole page grey!

CSS

Well, on the CSS part we will style the 'box' and 'screen' only!

#box
{
	width: 150px;
	height: 150px;
	background: #FFF;
	border: red dotted 5px;
	text-align: center;
	position: absolute;
	margin-left: -75px;
	margin-top: -75px;
	left: 50%;
	top: 50%;
	z-index: 20;
	display: none;
}

#screen
{
	position: absolute;
	left: 0;
	top: 0;
	background: #000;
}

These can be placed in jQuery code instead but since we want it to render faster, placing them in CSS will be a much better option(It really depend on you). Let me explain the 'box' CSS first.

  1. Give 'box' a width, height, background color and border so that it is visible on the screen
  2. align 'box' to center
  3. position it as absolute and make it visible(z-index) even when the screen is grey out
  4. margin-left/top,top,left are to align it on the center of the screen (cross browser) but in a fixed way
  5. we hide it (the display)

The 'screen' CSS is fairly easy to understand. We have to position it as absolute and align it at the top left hand corner so that it will cover the entire screen!

jQuery

Above section should be quite clear and simple. But, the jQuery code is even easier to understand.

$(function(){
var pop = function(){
	$('#screen').css({ opacity: 0.7, 'width':$(document).width(),'height':$(document).height()});
	$('body').css({'overflow':'hidden'});
	$('#box').css({'display': 'block'});
}
$('#button').click(pop);
});

The above should be quite basic. But the explanation are listed below,

  1. 'var pop = function(){..' wait until jQuery is ready!
  2. 'var pop = function(){..' create a function name 'pop'
  3. '$('#button').click(pop);..' attach an event handler, click onto the button
  4. '$('#screen').css({ opacity: 0.7, "w....' function activate we grey out the screen by providing the 'html' or 'page' width and height (instead of box size). This will cover the whole screen.
  5. '$('body').css({"overflow":"hidden"});' this is to fix the problem of using a 'fixed' center align CSS declaration
  6. '$('#box').css({"display": "block"});' this is to make the box appear!

It is really that easy! But going into grey out mode is simple, how about returning back to normal? Definitely, an extra event handler is required on the 'box' to reverse back the procedure!

$(function(){
var pop = function(){
	$('#screen').css({'display': 'block', opacity: 0.7, 'width':$(document).width(),'height':$(document).height()});
	$('body').css({'overflow':'hidden'});
	$('#box').css({'display': 'block'}).click(function(){$(this).css('display', 'none');$('#screen').css('display', 'none')});
}
$('#button').click(pop);
});

I have just added two things above, can you identify them?

The Demo

The above demo and files can be viewed from the following link.

Wait!

I'm not done (nagging)! If you notice, i made a cheat on top to simplify the overall complexity. And the cheat is 'overflow: hidden' on the jQuery code. But not all browser support this! How about those that doesn't?! This is where i add in additional component so that we do not have to even rely on 'overflow:hidden'!

The Problem And Solution

The problem with the above grey out screen effect was due to the 'box' (the cheat was for 'box' too). remained at the same position when we are scrolling which is a big NO NO. Therefore, we can either make the box to align fixed at the center or move along while the user scroll (persistence box). We have illustrated the cheat for screen grey out effect using jQuery. Now we will do the second one, the persistence box.

The Persistence Box

The answer to persistence box is located at Align center of the screen while scrolling with css What we have to do here is to change the CSS 'box' position: absolute to position: fixed. Of course, we will have to remove the overflow: hidden on the jQuery statement. This will make it chase after your scroller and urge your users to take action on the 'box'. The final CSS code will look like this,

#box
{
	width: 150px;
	height: 150px;
	background: #FFF;
	border: red dotted 5px;
	text-align: center;
	position: fixed;
	margin-left: -75px;
	margin-top: -75px;
	left: 50%;
	top: 50%;
	z-index: 20;
	display: none;
}

And we will remove overflow: hidden in jQuery and the final code will look like this,

$(function(){
var pop = function(){
	$('#screen').css({ opacity: 0.7, 'width':$(document).width(),'height':$(document).height()});
	$('#box').css({'display': 'block'});
}
$('#button').click(pop);
});

This look even shorter than the previous one! Finally, we get a complete screen grey out effect in it simplest form.

Update 25 September 2009****
Matt asked a very good question below, this method will caused the grey out box stuck due to the css being set to 'fixed'. Hence, minimize to maximum in window browser will caused the grey out to stuck at the minimize size. Here is one of the solution you can live with.

$(function(){
var pop = function(){
	$('#screen').css({	"display": "block", opacity: 0.7, "width":$(document).width(),"height":$(document).height()});
	$('#box').css({"display": "block"}).click(function(){$(this).css("display", "none");$('#screen').css("display", "none")});
}
$('#button').click(pop);
$(window).resize(function(){
	$('#box').css("display") == 'block'?pop.call($('#button')):"";
});
});

I added an event handler during resize, check whether the box is displayed and it was displaying during resize we overwrite the pop out box again. The demo page was also updated for this update.

Demo for persistence box

The demo can be viewed on the following link!

Tutorial: How to vertical align center on the screen while scrolling with CSS

I believe some of you out there also faced this problem where your container is align on the center of the screen but when the screen is too long, the scroll bar appeared and your box remained on the top of the screen and you say "oh shit!". Searching all over the internet and found only how container can be align on the center of the screen but not when it was scrolling? I think this article will solve your problem.

The Problem

We are assuming here that you have aligned your container at the center of the screen with position absolute. If you are still having this problem, you may want to visit How to align center on the screen when using position absolute with CSS. Once your container has aligned on the center of the screen. You meet the problem of having it follow you while you scroll down the screen. I like to say that the container is not persistence enough! Let's make it persistence to follow your scroller.

The Concept

Basically, you can solve your container not aligned on center while scrolling with the following concept:

  • You can create a code of jQuery/JavaScript to accomplish this by making your container chasing after your scroller. Thus, changing the container position on every scroller movement. (not good)
  • The other way is to just CSS (which we are doing) to cheat the above effect. Instead of chasing after the scroller, we fixed the position on the center of the screen while having absolute to cover all other elements!

We will be doing the second approach which is more efficient and is the more correct way of doing. The reason why it must be position fixed is that the container should not move! Thus, stay at the center of the screen when you scroll. As for the reason why it must also be position as absolute is because we need to cover up all element below to prevent any user from clicking on the elements!

The Solution

The Trick is fairly simple after you have accomplished your center alignment on the screen with absolute position. I take the following code from the article and change it so that the container will remain center while scrolling.

#box
{
	width: 150px;
	height: 150px;
	background: red;
	padding: 5px;
	border: #CCC solid 1px;
	text-align: center;
	position: fixed;
	margin-left: -75px;
	margin-top: -75px;
	left: 50%;
	top: 50%;
	
}

The above is the one was in the article given in the link. Now i will just change the styling a bit to red and size accordingly and the new code that will make it remain center will be as follow,

#box
{
	width: 150px;
	height: 150px;
	background: #000;
	padding: 5px;
	border: #CCC solid 5px;
	text-align: center;
	position: fixed;
	margin-left: -75px;
	margin-top: -75px;
	left: 50%;
	top: 50%;
}

The main changes done was 'position:fixed' which fixed your container at the center of the screen whenever it go! Persistence enough.

The Demo

The following links are the demo for persistence and non-persistence container: