Creating Pop-Up Notes with CSS and JavaScript Part I
A pop-up note contains information and can be made to appear when a visitor to your website moves the mouse over the appropriate area. Alejandro Gervasio explains how to create several different kinds of pop-up notes using CSS and JavaScript.
createNotes=function(){ showNote=function(){ // gets note1 element var note1=document.getElementById('note1'); // assigns X,Y mouse coordinates to 'note1' element note1.style.left=event.clientX; note1.style.top=event.clientY; // makes note1 element visible note1.style.visibility='visible'; }
hideNote=function(){ // gets note1 element var note1=document.getElementById('note1'); // hides note1 element note1.style.visibility='hidden'; }
var a1=document.getElementById('a1'); // shows note1 element when mouse is over a1.onmouseover=showNote; // hides note element when mouse is out a1.onmouseout=hideNote; }
// execute code once page is loaded window.onload=createNotes; </script>
<style type="text/css">
p { font: normal 11px "Verdana", Arial, Helvetica, sans-serif; color: #000; }
The visual output is illustrated in the following images, indicating X - Y mouse coordinates:
As we can appreciate from these screenshots, the pop-up note appears at the mouse coordinates, expanding the limits of the previous static example, and displaying a more polished look.
If we wish improve the script even more, we might replace the "onmouseover" event handler with the "onmousemove" event handler within the code. Doing so, the note will be displayed "chasing" the mouse pointer, implementing an additional effect that can be potentially more appealing to visitors. All we have to do is replace the following line:
a1.onmouseover=showNote;
with this:
a1.onmousemove=showNote;
and that's all. We have a fully functional pop-up note that is very useful to include in our pages. Are we done? Not quite.
Note that in its current from, this script doesn't scale very well, since we're manipulating a single pop-up note. We did this to simplify the script, just so it's easier to understand how the JavaScript code is manipulating CSS. The next logical step would be expanding out the limits of the script to handle any number of notes across the Web document, which is the goal initially intended. In Part 2, we'll cover the creation of multiple pop-up notes.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.