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.

Bookmarklet: Submit a login form using javascript within a bookmark

If you’re like me, you have many bookmarks to administration areas that require authentication. For you, this script is a priceless time-saver.

Let’s say your login page has a form similar to the following…

<form action="/login.php" method="post">
    <label>Username: <input type="text" name="user"></label>
    <label>Password: <input type="password" name="pass"></label>
    <input type="submit" value="Log In">
</form>

Some logins simply cannot be stored in the browser’s password system. So, to save you the extra effort of manually logging in on each visit to such pages, create a bookmark that automatically logs you into the system.

Here’s the code to submit that form using a bookmarklet… Continue reading

jQuery Add Bookmark to Favorites Script

Here is a quick example of how to use jQuery along with traditional browser sniffing techniques to create a dynamic “Bookmark Us” link.

Google CDN (latest 1.x version, theme)…

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<link type="text/css" rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1/themes/blitzer/jquery-ui.css" />

The javascript… Continue reading

Make the jQuery UI Datepicker use a jQuery Button

It has been bugging me for some time that the datepicker widget uses a normal button unless you tell it to use an image. Seeing that we are using the jQuery-UI framework, it makes sense to me that the button should be styled as such. After playing with the selectors and trying it a few different ways, here is how I made that boring datepicker button become a jQuery-UI button (with calendar icon). Continue reading

Submit ajax form in jQuery-UI Dialog with Enter Key

This question is posted quite a bit and nobody seems to be able to provide a good solution that won’t behave questionably. So here’s my take on it…

$('<div id="myDialog"></div>').appendTo('body').dialog({
    autoOpen: false,
    modal: true,
    closeOnEscape: true,
    buttons: {
        OK: function() {
            $.ajax({
                type: 'POST',
                url: 'save.php',
                data: $('#myDialog :input').serialize(),
                error: function(xml, status, error) {
                    $('#myDialog').html('<p><strong>Error Code:</strong> '+status+'</p><p><strong>Explanation:</strong> '+error+'</p>');
                }
            });
        },
        Cancel: function() {
            $(this).dialog('close');
        }
    },
    open: function() {
        $(this).html('').load('form.php');
    },
    focus: function() {
        $(':input', this).keyup(function(event) {
            if (event.keyCode == 13) {
                $('.ui-dialog-buttonpane button:first').click();
            }
        });
    }
});

Note: You can also trigger the event on any element (not just form fields) by using $(this) as the selector.

That’s it, enjoy 🙂

Change CodeIgniter’s Form_validation error delimiters globally!

I have seen this question all over the web and am surprised that nobody has actually offered such a simple solution.

Anyway, here is a quick, simple and painless way to set CodeIgniter’s error delimiters (used by the Form_validation library) one time for your entire application. Create “application/libraries/MY_Form_validation.php” with the following contents… Continue reading

Easily load multiple views with CodeIgniter

It is not uncommon to load a common header, footer and other views in each controller. While this can be achieved like so…

$this->load->view('header', $header_data);
$this->load->view('content', $content_data);
$this->load->view('footer', $footer_data);

I wanted the ability to do the same thing with a single line of code. So I decided to extend the core Loader library by creating “application/core/MY_Loader.php” with the following code… Continue reading

Disable browser cache easily with CodeIgniter

I have a project where users are validated by session data. When the user logs out I destroy the session and redirect them to the log-in page, but this does not prevent them from clicking the browser’s “back” button, in which case they still see the data.

My first solution was to set headers with PHP’s header() function. Then I decided to use CodeIgniter’s setheader() function from the Output library (no real difference, just using CI methods when possible). Finally, I decided the best way to do this would be to extend the Output library itself. This way I am not repeating multiple function calls in each controller. Here is end-result… Continue reading

Reset fields to default values using jQuery

Have you ever wanted to reset only fields in a particular section of the form without resetting all of the fields?

Here is how you can achieve this with jQuery 🙂

$('#reset_address').click(function (event) {
 event.preventDefault();
 $('#address_details :input').each(function() {
  if ($(this).is('select')) {
   $(this).val($(this).find('option[selected]').val());
  } else {
   $(this).val(this.defaultValue);
  }
 });
});

#address_details represents a <fieldset> within my <form>. When the user clicks the #reset_address link I revert the fields within the <fieldset> (not the entire form) back to their original values.

Note: defaultValue is a core JavaScript property. A conditional check for <select> was necessary since defaultValue only applies to <input> and <textarea> fields.

My ultimate .htaccess file for CodeIgniter 2.0

#Initialize mod_rewrite
RewriteEngine On
RewriteBase /

#Force "www" subdomain
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

#Re-route forbidden urls
RewriteCond %{REQUEST_URI} ^(system|application).* [OR]
RewriteRule ^(.*)$ index.php?/$1 [L]

#Re-route urls if file/directory does not exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

IMPROVED jQuery Image Preloader with Rollover Effect (dynamic extensions supported)

This post expands on my original jQuery Preload and Swap Navigation Images post. The original code required you to enter the file extension (eg: jpg, png, gif). The modifications below make this jQuery hover/rollover/swap code totally dynamic 🙂

$(document).ready(function() {
 //preload images
 var preloadedImages = new Array();
 $('#container img').each(function(i) {
 preloadedImages[i] = new Image();
 var ext = $(this).attr('src').split('.').pop();
 preloadedImages[i].src = $(this).attr('src').split('.' + ext).join('-hover.' + ext);
 });
 //rollover effect
 $('#container a').hover(function() {
 var ext = $(this).find('img').attr('src').split('.').pop();
 $(this).find('img').attr('src', $(this).find('img').attr('src').split('.' + ext).join('-hover.' + ext));
 }, function() {
 var ext = $(this).find('img').attr('src').split('.').pop();
 $(this).find('img').attr('src', $(this).find('img').attr('src').split('-hover.' + ext).join('.' + ext));
 });
});

The only significant change from my original code to grab the file extension (var ext = value) before preloading or swapping the images… Continue reading

Use location.hash to pre-select a jQuery UI tab

I have noticed quite a few people asking how to set a default tab during page load using the jQuery UI Tabs Widget. My method is as follows…

<script>
$(function(){
 $('#tabs').tabs({
  selected: (location.hash && parseInt(location.hash.substr(1)) != 'NaN') ? parseInt(location.hash.substr(1)) : 0
 });
});
</script>

I am checking the url for a hash value (eg: mypage.htm#3). If one is found and it can be parsed to an integer, it will use that number for the selected tab, otherwise it defaults to zero.

jQuery UI Tabs Widget documentation

If you are not familiar with the short-hand if/else syntax above, here is an example…

variable = (condition) ? true : false;

Written long-hand it would be…

if (condition) {
 variable = true;
} else {
 variable = false;
}