"We are 90% done. The code has compiled successfully."


Syndicate content

You are hereJavascript/css floating popup

Javascript/css floating popup

robo's picture

By robo - Posted on 06 February 2011

Sometimes it is nice to give your visitors an idea of where your external links will take them. To make this visually attractive, a nice device is a small popup window with a screenshot of the remote site and a short description. You can see how this works on the left hand side under 'Our other sites'. When you hover over the links, you get a floating popup showing you where you will be linked to.

The following code shows how you can easily create this effect. It creates hidden floating div containers that are shown using Javascript. This should work in all modern browsers. Even on the iPad you will get a preview the first time you touch it. A second touch will take you to the link, while touching the popup itself will close it.

First we define two Javascript functions to hide or show elements by their Id:

Then we define the layout and design of the popup itself. I am positioning the popup absolutely, 160 pixels to the left and 32 pixels down from the links (see the popup_container below). The z-index is set to 10, so that it will appear above the page (and any other elements lower than 10).

Then we get to the actual popups. Here they are defined statically, but you could of course create them dynamically (in Drupal using a view, e.g.). An important element is the popup_container div: when you absolutely position elements, so that they will float above other elements and more importantly, won't interfere with the layout, the position will be determined as an offset to the parent. But this only works when the parent has relative positioning. By wrapping the popup divs in a relatively positioned container (of which we know were it is placed) we can float the popup near the list of links.
Every popup has an Id that is used to show or hide it. For the content I use a small thumbnail of the site, with a short description. The class is set to the site_float defined earlier and the initial status is hidden (display: none).

Lastly we get to the actual list. Again this could be created using a view in Drupal or another technique. The main thing to notice is the onmouseover and onmouseout events. They will call the respective Javascript commands.

The code here is completely independent, so you can copy all four pieces of code (script, css and 2 html) into a Drupal Block and it will work after you configure the links and images. People with Javascript switched off, won't see the popups. One way of adding a simple text-only popup to your links is by setting the title="description" on the <a> tag. Most browsers will show this as a tooltip when the user hovers over the link.

- Robo