Category Archives: Code Snippets

Here you will find various snippets and code examples that I have used to make some thing in my life a little easier to deal with.

How to Add icons to Input (Submit and Reset) Buttons using jQuery UI

As you may have already noticed, most browsers do not support adding icons to <input type=”submit”> and <input type=”reset”> using jQuery UI. The code below will correct this issue by replacing matched <input> tags with appropriate <button> tags…

$(document).ready(function(){
 $('input:submit, input:reset').each(function(){
  $(this).replaceWith('<button type="' + $(this).attr('type') + '">' + $(this).val() + '</button>');
 });
});

We loop through each submit and reset button and replace it with a button tag using the original input’s value as the new button’s text. Since we are using the original input’s value attribute, it should not be considered optional. Otherwise, you’ll end up with a button that has no text unless you set it explicitly with the .button({label: ‘my button label’}) option unless you intend to show only the icon by calling .button({text: false}) option.

Now we can assign icons to the buttons without updating the html using the following code… Continue reading

Safe email mailto links using jQuery

Here is a quick and easy way to use jQuery for hiding email links from spam bots.

$(document).ready(function() {

 //safe mailto's
 $('a[href*="[at]"][href*="[dot]"]').each(function() {
  var email = $(this).attr('href').split('[at]').join('@').split('[dot]').join('.');
  $(this).attr('href', 'mailto:' + email.toLowerCase());
  if ($(this).text().length == 0) $(this).text(email);
 });
});

First things first… loop through all the anchor tags (aka: links) that have [at] and [dot] in the href attribute. Next replace those placeholders with the proper characters. Then we prepend mailto: and lastly update the inner text of the anchor tag with the email address.

To make this work, your email links would be written as follows… Continue reading

Adding mouse events to table rows using jQuery

In my example I will only be modifying the row’s css classes. The behavior would be very similar to what you may already be familiar with in phpMyAdmin’s interface.

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" /></script>
<script type="text/javascript">
$(document).ready(function() {
 $('tr').hover(function() {
  $(this).toggleClass('highlight');
 });
 $('tr').click(function() {
  $(this).toggleClass('selected');
 });
 $('tr:even').addClass('odd');
 $('tr:odd').addClass('even');
});
</script>

Everything should be pretty easy to understand except for the last 2 addClass commands. jQuery’s “:odd” and “:even” selectors behave differently than you may expect. You could assume the “odd” selector to start at the “first” row but that is not the case (an array’s first element zero-index unless otherwise defined). Unless I included a heading row, my “first” row is actually an even row since it is referenced as an array and has an index of zero. That’s why it looks like I am doing it backwards 😉

Open all external links in a new window using jQuery

In the following code we set the “target” attribute to “_blank” for every anchor that has an “href” attribute starting with “http(s)://”…

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" /></script>
<script type="text/javascript">
$(document).ready(function() {
 $('a[href^="http://"],a[href^="https://"]').attr('target','_blank');
});
</script>

Most examples of this type only check for links starting with “http”, this of course would cause internal relative links such as “httpd_info_page.html” to open in a new window. This is why I check specifically for the full strings.

jQuery Preload and Swap Navigation Images

UPDATED CODE: IMPROVED jQuery Image Preloader with Rollover Effect (extension independent)

I have been researching Javascript libraries quite a bit lately and have decided on jQuery. Don’t ask me to say why it is better or worse than the other libraries out there. After reading the documentation I just happen to prefer it.

Suprisingly enough, one of the most common things Javascript is used for is navigation rollovers. Swapping an image source using markup attributes such as onmousover and onmouseout is not difficult by any means. We have all done it the “old” way and most of us still do, but there is hope!

I normally use unordered lists for my menus, but for simplicity’s sake, and no need to reference CSS rules, here is an example of a very basic menu.

<div id="navWrapper">
 <a href="page1">
 <img src="../assets/images/page1.png" /></a>
 <a href="page2">
 <img src="../assets/images/page2.png" /></a>
 <a href="page3">
 <img src="../assets/images/page3.png" /></a>
</div>

Now what we would usually do is add “onmouseover” and “onmouseout” events to each anchor (link) and an “id” attribute to each anchor’s child image. Wouldn’t it be great if we didn’t have to clutter the (X)HTML with javascript? There must be a better way… this is the thought that started me on my introduction to jQuery 🙂

Using only the markup above and the Javascript referenced below, we can achive the same result of my previous Javascript image preloader/swapping function post. Continue reading

CodeIgniter Form Validation Callback Functions with Multiple Arguments

If you’re reading this you most likely already know that you can only send one argument to callback functions using CodeIgniter’s Form Validation Class. If you are not yet familiar with this feature/limitation, here is an example of how the callback works.

Here is our controller with a normal callback (_foo) and our multiple-argument callback function (_valid_login)… Continue reading

Set element’s CSS min-height using JavaScript minHeight

Recently I have been doing a lot of work on new sites that incorporate fixed-position footers (similar to the Facebook chat bar). A few examples sites are: Power Core USA and Douglas Stevens, MD (both of which I coded, graphic design by Brand Chemist). I ran into an issue with Power Core layout where the main content borders were not reaching the footer on larger displays in pages with small amounts of content (eg: not enough to activate scrollbars). So I ended up writing a quick JavaScript function to set the minHeight property of the DIVs causing the issue. Continue reading

Javascript Image Preloader with Image Swapping Function

In this post you will find a simple image swapping function that will work for all images that need a hover effect.

The ‘img’ argument is required of course. I can either be a reference the the image object itself (eg: swapImg(this)) or a string (eg: swapImg(‘ImageID’)) if calling the function from somewhere other than within the <img> tag. If no arguments are passed, it aborts execution. If a string is passed, we first make sure that getElementById is supported. Then we check to make sure the ID passed is valid, of not we return.

After ‘img’ has been checked and confirmed, we move on to the 2 optional arguments. The ‘find’ argument (case-sensitive) indicates the string we are looking for at the end of the image src attribute. If the string is found, we know that the image is currently in the ‘over’ state and we replace ‘find’ with ‘repl’ to return the image back to it’s normal state. On the other hand, if ‘find’ is not located, we rebuild the src attribute and insert ‘repl’ at the end of the image url (before the file extension) to activate the hover state. Continue reading

Disable/Hide Internet Explorer’s Compatibility View Button

If you are an active web developer, you have likely been plagued by Internet Explorer’s Compatibility View button. I have seen so much poor advice about disabling this feature in IE7+. Post after post after post people suggest forcing a specific version for emulation. Haven’t we all learned that allowing IE to dictate how we code a page is a BAD idea?

If you properly code your pages to use standards and a proper document type definition or <!DOCTYPE>, why does IE persist in not doing what it’s told and letting visitors make potentially baddecisions. A user can accidentally click the Compatibility View button or have compatibility mode always enabled by default (OMG!). If you want to make sure IE or the user doesn’t dictate how you code, or how the layout is butchered by compatibility view, add the following to your <head> section…

Continue reading

Validate email domain using PHP’s checkdnsrr with CodeIgniter

I recently noticed a bunch of garbage registrations for an existing client’s newsletter function written quite some time ago. After making a copy of the subscribers table and “cleaning” the data (proper-cased names, lowercased emails, etc), I started looking at ways to limit these automated registrations.

The client would not be happy with registration confirmation emails, so I decided to make a callback function for use with CodeIgniter’s Form Validation library. Since it was only needed in one location, this method made more sense to me than extending the main library.

Here is the function…

Continue reading

CodeIgniter, MySQL and User-Defined Variables

The lesson for today is… how to sort records sequentially on a numeric column and provide the ability to move records up and down in the existing sort order.

There are 2 functions I use for manual record sorting to change the display order in admin/user areas. The following example is based on a “pages” table and the commands are located in a model. For this example, the table has the following fields: page_id (int), page_sort (smallint), page_title (varchar), and page_content(text).

Continue reading

XHTML compliant external links based on anchor href attribute

The inspiration for this code was New-Window Links in a Standards-Compliant World. They were using the “rel” attribute and checking it for “external” to update the anchor’s target attribute. I lean towards not opening new windows unless it’s an off-site link to improve the user’s experience. Furthermore, I try to avoid adding more code when I can simply use an element’s existing attributes to serve my needs.

Continue reading