Easy Pop-Ups with JQuery

JQuery is a powerful Javascript framework and I recently wanted to use it to make a popup submenu for MausJewelers.com on non-touch devices. I also wanted to position the popup dynamically on pageload since I wasn’t sure where the link that would trigger the popup would be positioned since the site is responsive.
You start with a DIV that contains the content to be displayed that you can trigger using the OnMouseOver event on a link or other HTML element. You can hide the popup using the OnMouseOut event event. In this example, the popup is triggered when the user positions their mouse over the Showcase link as shown here:
Showcase Popup
The trickiest part comes when you want to trigger the popup but you want to allow the user to move their mouse over the popup without causing the popup to disappear since their mouse is leaving the link.
To achieve this, you need to set up a timeout mechanism that will allow you hide the popup only when the user is NOT hovering the link or the popup. After that it is a matter of positioning the popup so it is under the link (and the user can move between the link and the popup. Here is a bit of code that I used for Maus Jewelers.
<!-- The Nav menu, I am using Bootstrap so this will be hidden on extra small devices -->
<div class="header-bottom header-nav hidden-xs">
    <ul class="nav navbar-nav">
          <li class="<?php checkActive("Location", $section); ?>"><a href="/location">Location</a></li>
          <li class="<?php checkActive("Services", $section); ?>"><a href="/services">Services</a></li>
          <li class="<?php checkActive("About", $section); ?>"><a href="/about">About Us</a></li>
          <li class="<?php checkActive("Showcase", $section); ?>" onmouseover="openPopup();" onmouseout="closePopup(true);" id="link"><a href="/showcase">Our Showcase</a></li>
         <li class="<?php checkActive("Home", $section); ?>"><a href="/">Home</a></li>

<!-- The popup -->
<div id="popup" style="display:none; z-index:10; position:absolute; top: 135px;" onmouseover="openPopup();" onmouseout="closePopup(true);" class="popup hidden-xs">
     <!-- I manually position the div so it will be far enough down the on the page. In this case, the nav link will not change it's top position. I am also using Bootstrap so this will be hidden on extra small devices. -->
     Hello Popup.

<script type="text/javascript">
var enablePopup = true; // if set to false, we won't open a popup
var pixelOffsetFromLink = 75; // The number of pixels to move to the left, from the link, this helps to align the popup

// Global variables
var popupOpen = false; // Indicates if the popup is currently open
var popupTimer = null; // Is a timer that triggers the closePopup function

 * Calculate where the popup should be positioned based on where the link is currently at
 * @return null
function calculatePopupPosition() {
     var $popup = $("#popup");
     var $link = $("#link");
     $popup.css("left", ($link.offset().left - pixelOffsetFromLink) + "px");
     return null;

 * Close the popup if the popup is open and we don't want to set a timer
 * @param boolean setTimer: Indicates if we should set the timer and then close the popup after the timer's function is triggered
 * @return null
function closePopup(setTimer) {
     // Return if the popup isn't open
     if (!popupOpen) {
          return null;
     // If we have a popup timer already, clear it so we can make a new one
     if (popupTimer != null) {
          popupTimer = null;
     // If we have set the timer, we will return early but set a timer to trigger this function and actually close the popup
     if (setTimer) {
          popupTimer = window.setTimeout("closePopup(false);", 250);
          return null;
     // Check if the mouse is over the popup, if it is, keep the popup open

     // If we aren't hovering anymore, close the popup and remove the hover class from the link
     if ($("#link:hover").length == 0 && $("#popup:hover").length == 0) {
          popupOpen = false;

     return null;

 * Open the popup
 * @return null
function openPopup() {
     // If the popup is open or if we don't want to show a popup at all, return
     if (popupOpen || !enablePopup) {
          return null;
     popupOpen = true;
     // Give the link a hover class

     return null;

Wrapping HTML Elements with a Parent DIV using jQuery

One of our projects required us to add a target element to a parent DIV dynamically. In this example, we are targeting the “child” CSS class and adding any elements that have that CSS class to a DIV with the “parent” CSS class.

// Add a selector to a parent DIV with the wrapping class
var targetSelector = ".child";
$(targetSelector).each(function() {
// Check the parent doesn't already have the wrapperClass on it
var wrapperClass = "parent";
if ($(this).parent().hasClass(wrapperClass)) {

// Wrap the target element with a parent div with class = wrapperClass
var parent = document.createElement(“div”);
var $currNode = $(this).clone();

// Replace the current node with the parent and append the current node content

Overwriting the Browser Confirm pop up using jQuery

The browser’s default confirm function is a synchronous blocking function that usually pops up a dialog box causing a web page to stop executing code and wait for user input. In most browsers, the user is allowed to select “OK” or “Cancel” and developers usually have very little control over the confirm box other than the message displayed.

This can lead to some problems when the confirm box blends into the website such as in the case with Chrome 35.0 or when you simply want more control over the button options.

You can overwrite the default confirm function such as in the following snippet of code which combines jQuery UI and Bootstrap to create a nice looking confirm box that is easier to read.

It is important to note that you will still run into a problem if you attempt to write code that blocks until the user presses a button. For that reason, the code will fall back to the old confirm function if you don’t give it a function to call when you press the OK or the Cancel button.

<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<div id="wrap">
<div class="container">
<div class="row">
<div class="col-sm-12">

<h1>Overwrite the Browser's Default Confirm Box</h1>

<div id="status"></div>

	<a href="#" class="btn btn-default" onclick="confirm('Are you sure that you want to continue?', confirm_function1, cancel_function1); return false;">Click to confirm</a>

	<a href="#" class="btn btn-default" onclick="if (confirm('Are you sure that you want to continue?')) { confirm_function1(); } else { cancel_function1() }; return false;">Click to confirm using default confirm box</a>

<script type="text/javascript">
function confirm_function1() {
	$('#status').html('Pressed OK');

function cancel_function1() {
	$('#status').html('Pressed Cancel');

 * Replace the jQuery UI buttons styles in the confirm box with Bootstrap styles
 * @param string id: The jQuery object to update
 * @param string buttonClass: The button class to the give the button
 * @return void
function updateConfirmBoxButton(id, buttonClass) {
	var disableJqueryUICss = function() { 

		.prop("class", buttonClass)

// Adjust how the confirm box is rendered
window.default_confirm = window.confirm; // Save the old confirm box function in case we need to fallback to it

 * Create a new confirm box function
 * @param string message: The message to display
 * @param function confirm_function: The function to execute when the user presses the 'confirm' button
 * @param function cancel_function: The function to execute when the user presses the 'cancel' button
 * @return object: If confirm_function or cancel_function are null then return the value returned by the old confirm box function Else return the new confirm box object
window.confirm = function(message, confirm_function, cancel_function){
	// Fall back to the old default confirm box if we don't have both a confirm and cancel function
	if (confirm_function == null || cancel_function == null) {
		return window.default_confirm(message);

	// Create the new confirm box
	var confirmBox = document.createElement("div");
			dialogClass: "confirmBox",
			buttons: {
				"OK": {
					id: "OK",
					text: "OK",
					click: function() {
				"Cancel": {
					id: "Cancel",
					text: "Cancel",
					click: function() {
			close: function() {
			draggable: false,
			modal: true,
			resizable: false,
			width: 'auto'
	// Adjust the dialog box we just created
	// Update the background so it is higher contrast
	$(".confirmBox.ui-widget-content").css("background", "#fff");
	// Update the background so it is higher contrast and the buttons are centered
	$(".confirmBox .ui-dialog-buttonpane").css("background", "#fff").css("border-width", "0").css("padding", "0");
	$(".confirmBox .ui-dialog-buttonset").css("text-align", "center").css("float", "none");
	// Hide the Titlebar
	$(".confirmBox .ui-dialog-titlebar").hide();
	// Update the confirm box buttons
	updateConfirmBoxButton(".confirmBox .ui-dialog-buttonset #OK", "btn btn-success");
	updateConfirmBoxButton(".confirmBox .ui-dialog-buttonset #Cancel", "btn btn-danger");

	return confirmBox;


Automatically Link Text using VB.Net

At work, we use VB.net and one problem that I encountered involved a forum where they wanted to automatically link any words with http:// or https:// within the posts. Aside from security concerns, you can do this using the following script.

However, it is important to note, that it will only link URLS that are one word. You could modify the regular expression so that if a person put quotes around the URL, they could link the entire thing, but I am going to leave that to someone else.

' Function: LinkText()
'   Takes a msg and automatically adds HTML to link all words starting 
'    http:// or https:// in the text
' Parameters
'   Msg: Is the Message we want to link the links in
' Returns:
'   NewMsg: The linked the links in the text
Function LinkText(ByVal Msg As String)
	' Remove all hrefs (so we can replace them)
	Msg = Msg.Replace("", "")
	Msg = System.Text.RegularExpressions.Regex.Replace(Msg, "]*>?","")
	Dim MatchObj as MatchCollection = Regex.Matches(Msg,
	Dim NewMsg As String = Msg
	For Each m As Match In MatchObj
		NewMsg = System.Text.RegularExpressions.Regex.Replace(NewMsg, 
                              m.Groups(0).Value, "<a  
                              href=""" & m.Groups(1).Value & """>" 
                              & m.Groups(1).Value & "</a>"
                              & m.Groups(3).Value)
	Return NewMsg
End Function

Handling Default Values in Form Elements (with Javascript)

You can add some fancy Javascript functionality to your forms by handling how form elements behave when a user focuses and blurs focus on different elements. When they focus on the element, this script will help you check if they have already entered content into this element or if you should clear it. When they end their focus on the element, another function will fire and check if the element has a blank element and refill it with the default value. This comes in handy when you that element is required in the form. Try it out below, focus on the first element and then focus on the next one.

Email Parser

A form and downloadable script that parses the emails from a list of email addresses and names (or any text actually). This problem came up during work and for a quick solution, I made an html file that parses the input and looks for email addresses. For those interested in regular expressions, the parsing is done with the .match function in javascript using the following pattern: /[a-zA-Z\d\._\-]+@[a-zA-Z\d\.\-]+\.[a-zA-Z]{2,4}/ This pattern is suitable for this task but not the best, other more complex patterns are available to handle every possible email but this one will do for now.

Parse Email Addresses

List of Emails