Quick popup/overlay show and hide a layer with Javascript and CSS

css popup

Really quick and simple code in order to show or hide a layer on your webpage using Javascript.

Effectively what we do is define a layer in CSS and then write a couple of functions, one to set the visibility and position of the layer and the other to find the position on the page that it should appear. You can then add whatever you want inside the layer ready to be shown or hidden when a user clicks a link, or anyother way to activate the function.

Typically when we create a layer in CSS/ HTML it will appear inline in the page much like any other HTML element. We can position layers to be positioned either static, fixed, relative or absolute. This bit is important to know for our popup layer/ overlay and how to position it.

Static is where the layer appears in the page as it normally would where ever it’s placed in the code, much like an image in a page.

Fixed will allow a layer to stay in the same place in the browser window despite scrolling.

Relative is normally done with co-ordinates set from the layer’s original position on the page.

Absolute will mean the layer is positioned in relation to the parent element that it appears in or another given element in our case.

So first we declare our CSS.
We create a layer id using # and assign width, height, position, display and index parameters


Next we write our Javascript functions
We write a function to hide the layer, a function to show the layer and position it and a function to find the position of a given object to work out where to display the layer.


Finally we create our HTML
Here we create our layer and a couple of links, one to close the layer and one to open the layer, the function to open the layer needs the id of the layer to open and the object from which to position itself, in this case we use the link (this).


And here’s the final code:

	LUCKYLARRY.CO.UK - basic overlay, show/ hide a layer popup




  • Hmm – in FirFox 3.6, all your open and close links do is take you to the top of the page.

  • as RationalRabbit says, but it is the same in Internet explorer

  • sry but is %MINIFYHTMLa854251d36ca054a6f295b4ca926a6773% standing for some codesnippets of js ? this doesnt really help me since i was looking for hints which js to use :/

    • sorry look like the blog was on the fritz again – the code snippers should be back there now

You must be logged in to post a comment.