Pop-up Image Widget using JavaScript, PHP and CSS

Exclusive offer: get 50% off this eBook here
Object-Oriented JavaScript

Object-Oriented JavaScript — Save 50%

Create scalable, reusable high-quality JavaScript applications and libraries

$23.99    $12.00
by Roshan Bhattarai | April 2009 | AJAX

In this article by Roshan Bhattarai, we learn how to build a widget similar to the Mybloglog widget using external JavaScript along with PHP. By the time we finish, you would see a popup image whenever you move the mouse cursor over the widget. In the later section, you can see an example for extracting image details from a database and using it in the example.

If you’re a regular blog reader then it’s likely that you’ve encountered the Recent Visitors widget form (http://mybloglog.com). This widget displays the profile like name, picture and sites authored by members of Mybloglog who have recently visited your blog. In the Mybloglog widget, when you move the mouse cursor to the member’s picture, you’ll see a popup displaying a brief description of that member.

A glance at MyBlogLog widget

Pop-up Image Widget using JavaScript, PHP and CSS

The above image is of a MyBlogLog widget. As you can see in the right part of the widget, there is a list of the recent visitors to the blog from members of MyBlogLog. You may also have noticed that in the left part of the widget is a popup showing the details and an image of the visitor. This popup is displayed when the mouse is moved over the image on the widget.

Now, let’s look at the code which we got from MyBlogLog to display the above widget.

<script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://pub.mybloglog.com/comm3.php?mblID=2007121300465126&r=
widget&is=small&o=l&ro=5&cs=black&ww=220&wc=multiple">
</script>

In the above script element, the language and type attributes are not specified. Although they are optional attributes in HTML - you must specify a value in the type attribute to make the above syntax valid in an XHTML web page.

If you closely looked at the src attribute of the script element, you can see that the source page of the script is a .php file. You can use the JavaScript code with any file extension like .php , .asp, and so on , but whenever you use such a file in src attribute please note that the final output code of the file (after being parsed by server) should be a valid JavaScript code.

Creating pop-up image widget

This pop-up image widget is somewhat similar to MyBlogLog widget but it is a simplified version of that widget. This is a very simple widget with uses JavaScript, PHP and CSS. Here you’ll see four images in the widget and a pop-up image (corresponding to the chosen image) will be displayed when you move the mouse over it. After getting the core concept, you can extend the functionality to make this look fancier.

Pop-up Image Widget using JavaScript, PHP and CSS

Writing Code for Pop-up Image Widget

As I’ve already discussed, this widget is going to contain PHP code, JavaScript and a little bit of CSS as well. For this, you need to write the code in a PHP file with the .php extension.

First of all, declare the variables for storing the current mouse position and string variables for storing the string of the widget.

var widget_posx=0;
var widget_posy=0;
var widget_html_css='';

The widget_posx variable is to hold the x co-ordinate values of the mouse position on the screen, whereas, the widget_posy variable will store the y co-ordinate. The widget_html_css variable stores the HTML and CSS elements which will be used later in the code.

The (0,0) co-ordinate of the output devices like monitor is located at the top left position. So the mouse position 10,10 will be somewhere near the top left corner of monitor.

After declaring the variables, let’s define an event handler to track the mouse position on the web page.

document.onmousemove=captureMouse;

As you can see above, we’ve called a function captureMouse() When the mouse is moved anywhere on the document (web page), the event handler which is the function captureMouse() is called on the onmousemove event. The Document object represents the entire HTML document and can be used to access and capture the events of all elements on a page.

Each time a user moves the mouse one pixel, a mousemove event occurs. It engages system resources to process all mousemove events, hence, use this event carefully!

Now, let’s look at the code of the captureMouse() function.

function captureMouse(event)
{
if (!event){var event = window.event;}
if (event.pageX || event.pageY)
{
widget_posx = event.pageX;
widget_posy = event.pageY;
}
else if (event.clientX || event.clientY)
{
widget_posx = event.clientX;
widget_posy = event.clientY;
}

}

As you can see in the above function, the event variable is passed as a function parameter. This event variable is the JavaScript’s Event object. The Event object keeps track of various events that occur on the page, such as the user moving the mouse or clicking on the link, and allows you to react to them by writing code which is relevant to the event.

if (!event){var event = window.event;}

In the above code, the first line of the event handler ensures that if the browser doesn’t pass the event information to the above function, then we would obtain it from any explicit event registration of the window object.

We can track different activity in the document by the event object with the help of its various defined properties. For example, if eventObj is the event object and we’ve to track whether the ctrl key is pressed (or not) - we can use the following code in JavaScript: eventObj.ctrlKey

If we’ve assigned the x, y-position of mouse in the page using the pageX and pageY properties, we can also get the same mouse position of the mouse cursor using clientX and clientY property. Most browsers provide both pageX/pageY and clientX/clientY. Internet Explorer is the only current browser that provides clientX/clientY, but not pageX/pageY.

To provide cross-browser support, we’ve used both pageX/pageY and clientX/clientY to get the mouse co-ordinates in the document, and assigned them to the widget_posx and widget_posy variables accordingly.

Now, let’s look at widget_html_css variable, where we’re going to store the string which is going to be displayed in the widget.

widget_html_css+='<style type="text/css">';
widget_html_css+='.widgetImageCss';
widget_html_css+='{ margin:2px;border:1px solid
#CCCCCC;cursor:pointer}';
widget_html_css+='</style>';

As you can see in the string of the above variable, we’ve added the style for the HTML element with the class name widgetImageCss within the style element. When applied, this class in the HTML adds a 2 pixel margins ‘brown color border’ to the element. Furthermore, the mouse cursor will be converted into pointer (a hand) which is defined with the cursor attribute in CSS.

widget_html_css+='<div id="widget_popup"
style="position:absolute;z-index:10; display:none"
>&nbsp;</div>';

Using the above code, we’re adding a division element with id widget_popup to the DOM. We’ve also added style to this element using inline styling. The position attribute of this element is set to absolute so that this element can move freely without disturbing the layout of the document. The z-index property is used for stacking the order of the element and in the above element it is set 10 so that this element will be displayed above all the other elements of the document. Finally, the display property is set to none for hiding the element at first. Afterwards, this element will be displayed with the pop-up image using JavaScript in the document.

Elements can have negative stack orders i.e. you can set the z-index to -1 for an element. This will display it underneath the other elements on the page. Z-index only works on elements that have been positioned using CSS (such as position:absolute).

Now, the PHP part of the codes comes in. We’ve used PHP to add the images to the widget_html_css string variables of JavaScript.

We’ve used PHP in this part rather than using JavaScript for making this application flexible. JavaScript is a client side scripting language and can’t access the database or do any kind of server activity. Using PHP, you can extract and display the images from the database which might be the integral part of your desired widget.

Object-Oriented JavaScript Create scalable, reusable high-quality JavaScript applications and libraries
Published: July 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Here is the PHP code for displaying the first image in the widget.

echo 'widget_html_css+='<img class="widgetImageCss"
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://yourhost.com/popupwidget/photo1_thumb.jpg"
onmouseover="changePopupAttribute('photo1.jpg')"
onmousemove="changePopupPosition()" onmouseout="hidePopup()"
/>'; ';

The backslash() is used to escape characters in the string. For example the statement, echo ‘O'brian’; in PHP produces the parser error. To output O'brian via PHP in the above statement we need to escape the single quote(‘) character in the middle of O'brian which can be accomplished with the following PHP statement : echo ‘O'brian’;

As the above PHP get parsed in the server, the following JavaScript code comes as an output to the client.

widget_html_css+='<img class="widgetImageCss" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://
yourhost.com/popupwidget/photo1_thumb.jpg"
onmouseover="changePopupAttribute('photo1.jpg')"
onmousemove="changePopupPosition()" onmouseout="hidePopup()"
/>';

As you can see in the above JavaScript string, three different functions are called on the three different events for the images of the widget. The changePopupAttribute() function is called on the mouseover event , while the changePopupPosition() method is called on the mousemove event. Conversely, the hidePopup() function is called on the mouseout event of the Image.

The difference between onmousemove and onmouseover event is that the onmouseover event is called whenever the mouse pointer gets over a specified object, and the onmousemove event is called at any time when the mouse cursor moves while it is over the specified element. Similarly, onmouseout event is called when the pointer moves away from the specified object.

After adding the widget content to widget_html_css variable, you can write it to the document using document.write() function.

document.write(widget_html_css);

Now, let’s look at the code of these three event handler functions changePopupAttribute(), changePopupPosition() and hidePopup().

function changePopupAttribute(imageVal)
{
document.getElementById('widget_popup').innerHTML='<img border="0"
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://yourhost.com/popupwidget/'+imageVal+'"/>';
document.getElementById('widget_popup').style.display='inline';
}

This changePopupAttribute() function is called on the onmouseover event of the images in the widget. This function takes the pop-up image name as parameter. As you can see in the first line of the above function, the supplied image is placed in the pop-up element using innerHTML property.

In the second line of above function, the display property of the element is set to inline using the style object to display the pop-up element. You can recall that this pop-up element is hidden when it is first loaded.

You can use the display property to show and hide the element using JavaScript. As the above code uses inline property to show the element, you can hide the element by assigning a ‘none’ value to the display property as shown below :

element.style.display=’none’;

The code of the changePopupPosition() function is given below :

function changePopupPosition()
{
document.getElementById('widget_popup').style.left=widget_posx+40+"px";
document.getElementById('widget_popup').style.top=widget_posy+"px";
}

As you can clearly see, this function just changes the position of pop-up element using the left and top properties of the style object. The widget is displayed 40 pixels to the right from the current mouse cursor position which is stored in widget_posx and  widget_posy variables.

Don’t be confused by this code widget_posx+40+"px". The plus(+) operator in JavaScript is used for two purposes: first for adding two numbers and second for concatenation of string. When two operands acting upon this operator are of number type, then this operator acts as a summation operator. If one of the operands is of string type, then this operator acts as a string concatenation operator.

Now, finally look at the code of the hidePopup() function which is called when the mouse is moving away from the widget images.

function hidePopup()
{
document.getElementById('widget_popup').style.display='none';
}

As you can see, this function does nothing more than hiding the element which contains the pop-up image.

Putting the code all together

Now, create a popup-widget.php file, add the given code below and save it. Since we’ve dissected the code in sections and just showed the PHP code for single image above, we’ll include it in an unabridged form below:

//position for variables
var widget_posx=0;
var widget_posy=0;
var widget_html_css='';

//track the position of mouse
document.onmousemove=captureMouse;

//function to capture mouse ent
function captureMouse(event)
{
if (!event){var event = window.event;}
if (event.pageX || event.pageY)
{
widget_posx = event.pageX;
widget_posy = event.pageY;
}
else if (event.clientX || event.clientY)
{
widget_posx = event.clientX;
widget_posy = event.clientY;
}
}

//function to change different attribute of the pop-up element
function changePopupAttribute(imageVal)
{
document.getElementById('widget_popup').innerHTML='<img
border="0" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http:// yourhost.com/popupwidget /'+imageVal+'"/>';
document.getElementById('widget_popup').style.display='inline';
}

//function to show the pop-up element
function changePopupPosition()
{
document.getElementById('widget_popup').style.left=widget_posx+40+"px";
document.getElementById('widget_popup').style.top=widget_posy+"px";
}

//function to hide the pop-up element
function hidePopup()
{
document.getElementById('widget_popup').style.display='none';
}
widget_html_css+='<style type="text/css">';
widget_html_css+='.widgetImageCss';
widget_html_css+='{ margin:2px;border:1px solid
#CCCCCC;cursor:pointer}';
widget_html_css+='</style>';
widget_html_css+='<div id="widget_popup"
style="position:absolute;z-index:10;display:none">&nbsp;</div>';
<?php
//please write the images here from server side scripting
echo 'widget_html_css+='<div>'; ';
echo 'widget_html_css+='<img class="widgetImageCss"
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://yourhost.com/popupwidget/photo1_thumb.jpg"
onmouseover="changePopupAttribute('photo1.jpg')"
onmousemove="changePopupPosition()" onmouseout="hidePopup()" />'; ';
echo'widget_html_css+='<img class="widgetImageCss"
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://yourhost.com/popupwidget/photo2_thumb.jpg"
onmouseover="changePopupAttribute('photo2.jpg')"
onmousemove="changePopupPosition()" onmouseout="hidePopup()" />'; ';
echo 'widget_html_css+='<br />'; ';
echo'widget_html_css+='<img class="widgetImageCss"
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://yourhost.com/popupwidget/photo3_thumb.jpg"
onmouseover="changePopupAttribute('photo3.jpg')"
onmousemove="changePopupPosition()" onmouseout="hidePopup()" />'; ';
echo'widget_html_css+='<img class="widgetImageCss"
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://yourhost.com/popupwidget/photo4_thumb.jpg"
onmouseover="changePopupAttribute('photo4.jpg')"
onmousemove="changePopupPosition()" onmouseout="hidePopup()" />'; ';
echo 'widget_html_css+='</div>'; ';
?>
document.write(widget_html_css);

Extracting image detail from database

In the above code, we have hard coded the image detail in the PHP code. In this section, I’ll quickly show you how to use image detail from the database and display it in widget.

Let’s suppose that the names of the images are stored the MySQL database with the table name tbl_image. The image names are stored in the image_big column and names of image thumbnails are stored in image_thumb column of tbl_image.

You can use the following PHP code to display the image details from the database.

<?php
//include the file containing database connection
include_once("db_connect.php");
//initialize the variable starting from zero
$i=0;
//get the images detail from table
$result=mysql_query('SELECT image_thumb, image_big FROM tbl_image');
while($row=mysql_fetch_assoc($result))
{
//increment the counter
$i++;
//write the image detail
echo 'widget_html_css+='<img class="widgetImageCss"
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://localhost/bookcode/popupimage/'.$row['image_thumb'].'"
onmouseover="changePopupAttribute(''.$row['image_big'].'')"
onmousemove="changePopupPosition()"
onmouseout="hidePopup()" />'; ';
if($i%2==0)
echo 'widget_html_css+='<br />'; ';
}
?>

As can be seen from the above code, first of all the file which connect the database is included. After that, image name is extracted from table tbl_image by executing the query and using two PHP function – mysql_query() and mysql_fetch_assoc(). The mysql_query() function returns the resultset data which is afterwards fetched into associative array by using the PHP function mysql_fetch_assoc().

Using Pop-up Image widget

To use this Pop-up Image widget we’ve to follow these steps:

  1. We need to upload the above popup-widget.php to a PHP enabled web server so that it can be used by the client websites. Let’s suppose that is uploaded and placed in the URL : http:// yourhost.com/popupwidget/popup-widget.php
  2. Now, we can widget in any web page by placing the following JavaScript Code in the website.
<script type="text/javascript" language="javascript" 
src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://yourhost.com/popupwidget /popup-widget.js"></script>

Summary   

In this article, we saw a different kind of widget which used a PHP file for the operations of the JavaScript code. Initially the image details are hard coded for a simple example in the PHP coding part. In the later section, you can see the example for extracting image details from a database and using it in the example.

If you have read this article you may be interested to view :

 

Object-Oriented JavaScript Create scalable, reusable high-quality JavaScript applications and libraries
Published: July 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Roshan Bhattarai is an experienced web developer. His core proficiency lies in JAVASCRIPT, CSS, XHTML, PHP and MySQL. Having done his masters in information technology, he has many active websites to his credit. He has worked in various companies as a Technical Lead before moving on as a freelancer. He primarily resolves problems faced by programmers, liaise with the clients to have a better understanding of the projects' requirement and does research on new technologies relating to the project. He also excels in analysis and design of the database and work flow of a web project. He also excels in analysis and design of the database and work flow of a web project. He can be contacted on his blog http://roshanbh.com.np.

Books From Packt

Object-Oriented JavaScript
Object-Oriented JavaScript

Learning jQuery 1.3
Learning jQuery 1.3

Magento: Beginner's Guide
Magento: Beginner's Guide

Drupal 6 Site Builder Solutions
Drupal 6 Site Builder Solutions

Joomla! E-Commerce with VirtueMart
Joomla! E-Commerce with VirtueMart

ASP.NET 3.5 Social Networking
ASP.NET 3.5 Social Networking

Drupal 6 JavaScript and jQuery: RAW
Drupal 6 JavaScript and jQuery: RAW

jQuery UI 1.6: The User Interface Library for jQuery
jQuery UI 1.6: The User Interface Library for jQuery

Your rating: None Average: 4 (2 votes)
Issue by
You create a popup-widget.php file and you embed a popup-widget.js file?? i dint got this

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
s
C
Q
K
L
G
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software