Oct 23

Match Numbers using RegExp

Since I use JavaScript as one of my primary development languages, I tend to need little helper functions to accomplish small tasks. One in particular I’ve needed more than any other is the ability to match a number, no matter how it was formatted. I found the following RegExp expression that has worked well for me in all my projects. It will match whole numbers (1, 2, 100, etc), decimals (1.01, 3.14, 100.50, etc) and comma formatted numbers (1,001, 10,375.34, 4,368,326.75). Hopefully this helps you as well.

```// match a number
function matchNumber(num) {
var result = /(?:^|\s)([1-9](?:\d*|(?:\d{0,2})(?:,\d{3})*)(?:\.\d*[1-9])?|0?\.\d*[1-9]|0)(?:\s|\$)/.test(num);
return result;
}
```

Here is a test fiddle I made: http://jsfiddle.net/dLne8219/

Any comments or questions let me know!

Oct 30

Format Phone Numbers in JavaScript

Here is a quick function that will grab any group of integers from a string so you may format phone numbers (or any number based formatting) quickly. By default this function formats phone numbers in standard 7 digit or 10 digit formatting. Example: 123-4567 and (123) 456-7890. The function matches all digits from a string. If a grouped match is found it checks the group length for the proper amount of numbers. If only one match is found it checks the single match for the length to determine if it is 7 or 10 digit. This can be easily modified to include country codes or a different string format if necessary. Hope this helps.

```function FormatPhoneNumber(num) {
var str = num.toString();

var matched = str.match(/\d+\.?\d*/g);

// 10 digit
if (matched.length === 3) {
return '(' + matched[0] + ') ' + matched[1] + '-' + matched[2];
// 7 digit
} else if (matched.length === 2) {
return matched[0] + '-' + matched[1];
}
// no formatting attempted only found integers (i.e. 1234567890)
else if (matched.length === 1) {
// 10 digit
if (matched[0].length === 10) {
return '(' + matched[0].substr(0, 3) + ') ' + matched[0].substr(3, 3) + '-' + matched[0].substr(6);
}
// 7 digit
if (matched[0].length === 7) {
return matched[0].substr(0, 3) + '-' + matched[0].substr(3);
}
}

// Format failed, return number back
return num;
}
```

Oct 29

SharePoint 2013 Workspace Scroll Issue Fix

Some of you may have run into an issue using SharePoint 2013 where the SharePoint created div #s4-workspace does not properly set the height and width of the workspace container. I have run into this problem for accounts not granted administrative privileges (the accounts that are unable to see the SharePoint ribbon). A quick fix for this is to ignore why SharePoint won’t do this and add a method to achieve this yourself. This probably isn’t the best solution but it does make things easier when trying to get an environment fully functional for testing before deploying to Production. To do this you will need to utilize the jQuery library. Any comments or questions let me know.

```function FixWorkspace() {
// if you are using a header that is affixed to the top (i.e. SharePoint Ribbon) put the ID or class here to change the workspace height accordingly.
var width = \$(window).width();
var height;
height = \$(window).height() - \$(header).height();
} else {
height = \$(window).height();
}
\$('#s4-workspace').width(width).height(height);
}

FixWorkspace();
});

\$(window).resize(function() {
FixWorkspace();
});
```

Jul 07

Verify jQuery Version is at Least 1.x.x

Small function to verify if the jQuery library loaded is at least version 1.x.x (where you define the minimum version). Note this function does NOT need jQuery loaded to work, so you can use it to check if jQuery is loaded and version compare if you wish.

```if (jqueryGreaterThan('1.4.4'))
{
// jQuery passed version verification, continue with your script...
}

function jqueryGreaterThan(requiredVersion)
{
var currentVersion = window.jQuery.fn.jquery;
var intCurrentVersion = parseInt(currentVersion.replace(/\./g, ""));
var intRequiredVersion = parseInt(requiredVersion.replace(/\./g, ""));

if (intCurrentVersion >= intRequiredVersion)
return true;
else
return false;
}
```

Jun 30

Attach .scroll() to AJAX loaded content

If you need to listen for a scroll event on AJAX loaded content that is not the window.scroll or document.scroll you may have realized that the .scroll() event does not bubble. All hope is not lost, you can still achieve this (especially if you are needing to do it with an element with overflow:auto; or overflow:scroll;) Using jQuery I can show you a very simple way to do this.

```
\$('#myAJAXContent').wrap('<div id="wrapper"></div>');

\$("#wrapper").on('scroll', function() {
// do stuff
});

```

Any questions or comments feel free to reply.

Apr 18

CSS2 Background Compliant Vignette

We all love the look and feel of vignettes on websites, however short of using CSS3 to display them as a background image, we are stuck using “hackish” CSS2 styling to achieve a 100% width vignette. Since my customers usually demand cross browser compatibility, I have developed a CSS2 compliant way of achieving a 100% width vignette. To do this, you’ll need to break up your vignette into 3 images. The left, middle, and right.

Left Vignette

Middle Vignette

Right Vignette

Once you have your vignette properly broken up, time to insert your vignette into your CSS.

```body {
background: url('images/bg/Header_Left.gif') no-repeat 0 0,
url('images/bg/Header_Right.gif') no-repeat 100% 0,
url('images/bg/Header_Middle.gif') repeat-x 30% 0;
}
```

Your website should have a vignette similar to this:

This is only required if utilizing multiple background images. If your vignette is the only background image you need, simply use CSS: body { background: url(‘my-vignette.gif’) no-repeat; }

Tested on Internet Explorer 9+, Firefox 5+, Chrome 12+, Safari 5+
For IE8 and lower, sorry folks your stuck only using the “hackish” absolute/relative positioned `<img />` tags.

Apr 14

PHP Rewrite URLs using Output Buffer

I recently was in need of replacing URLs to SEO friendly ones, the only hiccup was I wanted to maintain the PHP \$_GET params in the source code. As this is tried and true, and mod_rewrite can have its hiccups now and then. So after some research I found a solution that fit me perfectly. Using PHP’s output buffer I can utilize a callback function and a few preg_replace() functions to achieve all the necessary rewrites. And if for some reason I do not want to have rewrites enabled, I can comment out the callback and all my PHP URLs are back in place with no need for code editing. Here’s my example.

```<?php

// initialize output buffer to compress page.
// note: I recommend using 'ob_gzhandler' for pages >5kb. Any smaller its not worth it.
ob_start('ob_gzhandler');

// call the rewrite function.
HandleRewrite();

// do your page stuff...
echo '<a href="index.php?subpage=MYPAGE">Hello World!</a>';

// handle the URL rewriting
function HandleRewrite()
{
// rewrite URLS from output buffer
// note: it is IMPERATIVE this function is ABOVE the ob_start('rewrite') callback.
function rewrite(\$buffer)
{
// this preg_replace changes "mysite.com/index.php?subpage=TEST to mysite.com/TEST
\$buffer = preg_replace('/index.php\?subpage=(\w)/is', "\$1", \$buffer);
return \$buffer;
}

// start the output buffer for rewriting ('rewrite' being the callback function)
ob_start('rewrite');
}

?>
```

Utilizing this method makes it so your entire page can be re-written to any mod_rewrite (or whatever SEO utility you use) without search/replace of every link in your code.

As always, if you have any questions or comments, please reply.

Mar 20

Replace default hashtag scrolling in browser

Tired of the fluid-less jumps when going to a URL with a #hashtag? You can replace this using jQuery’s .scrollTo() method in the document.ready of your javascript. Here’s an example:

```\$(document).ready(function() {
if(window.location.hash)
{
\$('html, body').animate({
scrollTop: \$(window.location.hash).offset().top
}, 1000);
}
});
```

Now on page load this will fluidly scroll to the DOM element you’ve requested. I have not added error handling if say, the hashtag does not exist in the DOM, but you get the general idea.

Feb 19

jQuery UI Rename Tabs

I found myself in the position of needing jQuery UI’s tabs plugin to have the option of being renamed while still maintaining the tab. I came up with this function to easily rename a tab by passing the tab’s id selector and desired value.

```function renameTab(selector, value)
{
\$('a[href="' + selector + '"').text(value);
}
```

Keep in mind you should be using jQuery UI’s example of adding tabs template

```<div id="tabs">
<ul>
<li><a href="#tab-1">Tab 1</a></li>
<li><a href="#tab-2">Tab 2</a></li>
</ul>
</div>
```

This will work even if you are calling the href to load remote content via AJAX since the tabs use a unique identifier for those (i.e. #ui-tabs-1, #ui-tabs-2, etc.).

Simply rename “Tab 1” to “Tab 1337”

```renameTab("#tab-1", "Tab 1337");
```

Any questions/insight feel free to reply.

Nov 17

Move Row Up/Down with MySQL/PHP

Want to move rows with a click of a link and not have to worry about text boxes with position ID’s in them? Use this script/query to achieve this. Basically the idea is to have in your items table where it contains all the records you potentially want to move. In that table add a column named “position” with a unique integer for each new item you insert (do this by using a MAX(position) query when inserting the new item. It is imperative you have this unique integer or your results will not be fluid. Once that’s done copy and paste the following code to your website, filling in the proper variables indicated in the code. My method takes the previous (or next) record found from the current record (depending on whether you want to move it up/down, and swaps the position columns with each other. Then all you need to do for your table listing is “ORDER BY position” to have your items neatly sorted based on user or administrative preference.

```// Variables -- Fill these out from the results of your page. (i.e. what item id to move up or down)
\$id_item = 1;	// ID of item you want to move up/down
\$isUp = true;	// Change to false if you want to move item down

// MySQL structure -- Fill these out to execute your queries without needing to update my code
\$table_name = "tbl_items";	// Name of table with your items in it
\$col_position = "position";	// Name of column with position ID (Remember, this must be UNIQUE to all items)
\$col_id = "";			// Name of column containing the items id (most likely the auto_incremented column)

if (\$isUp)
{
\$operator = "<";
\$order = "DESC";
}
else
{
\$operator = ">";
\$order = "ASC";
}

// Get row we are moving
\$request = mysql_query("
SELECT '.\$col_position.', '.\$col_id.' FROM '.\$table_name.'
WHERE '.\$col_id.' = '.\$id_item.'
LIMIT 1");

// Save data for row we are moving
if(mysql_num_rows(\$request) > 0)  {
\$isPos1 = true;
while(\$row = mysql_fetch_assoc(\$request)) {
\$position1 = \$row[\$col_position];
\$id_item1 = \$row[\$col_id];
}
}

// Get row we want to swap with
\$request2 =  mysql_query("
SELECT '.\$col_position.', '.\$col_id.' FROM '.\$table_name.'
WHERE '.\$col_position.' '.\$operator.' '.\$position1.'
ORDER BY '.\$col_position.' '.\$order.' LIMIT 1");

// Save data from row we want to swap with
if(mysql_num_rows(\$request2) > 0)  {
\$isPos2 = true;
while(\$row = mysql_fetch_assoc(\$request2)) {
\$position2 = \$row[\$col_position];
\$id_item2 = \$row[\$col_id];
}
}

// If both rows exist (indicating not top or bottom row), continue
if (\$isPos1 && \$isPos2)
{
\$query_update = mysql_query("
UPDATE '.\$table_name.'
SET '.\$col_position.' = '.\$position2.'
WHERE '.\$col_id.' = '.\$id_item1.'");

\$query_update2 = mysql_query("
UPDATE '.\$table_name.'
SET '.\$col_position.' = '.\$position1.'
WHERE '.\$col_id.' = '.\$id_item2.'");
}
```

Any questions or issues with this method please reply.