Category: JQuery

Using JQuery To Open External Links In A New Window

19 February, 2010 | JQuery | No comments

Opening external links in a new window can be useful, but adding target="_blank" can be a real chore. Not only that, but if you are trying to validate the page to XHTML strict then the target attribute will cause errors to appear as it is not defined in XHTML.

An easy solution to this issue is to add the following JQuery to your site. It will look for any links that start with http and do not contain the current domain and add a new click event to them that causes a new window to be opened. This will exclude most links straight away as they will most likely be relative.

$("a[href^='http']:not([href*='example.com'])").click(function(){  window.open(this.href);  return false; }).attr("title", "Opens in a new window");

This code will also add a new title to each link, replacing any that already exist, just remove the call to attr() at the end of the block to stop this. If you are using this on your site then make sure you put this into a dom ready block, and also that you change the example.com to be your own domain name.

Written by Philip Norton.

Scroll To First Error Message On Page With jQuery And ScrollTo

29 January, 2010 | JQuery | 1 comment

If you have a large page or form that uses validation on it then you will probably want to tell the user that something is going on. One way to do this is by telling the user at the top of the page that something has gone wrong and then letting them figure out where.

A more elegant solution is to scroll the page down the just above the first error message so that the user is aware of what they need to fill in. This can easily be done through a combination of jQuery and the ScrollTo plugin.

The first thing you need on the form is add some tags as the error output elements. Make sure that these tags don't get printed if there are no errors. I have chosen to use p tags with the class of error. Download this plugin and include it within your page.

<p class="error">There was a problem with this element.</p>

All that is needed now is to tell ScrollTo that we want to scroll to the first error message on the screen. We can do this by using the filter "p.error:1" which will find the first p tag with a class of error on the page. You could also use the ":first" filter instead of this, but both have the same outcome.

This gets passed to the ScrollTo plugin in the following way.

$.scrollTo($('p.error:1'));

The slight problem here is that this scrolls the page down so that this element is flush with the top of the page, which makes sense if the error is above the element. If the error is below the element then you will need to set and offset so that there is enough space between the top of the page and the error message to fit the form element in. This is done through use of the offset option and a negative value, like this.

$.scrollTo($('p.error:1'), {offset: {top:-200}});

The good thing about this is that you can add to any form quite easily and it will have no effect unless there is a paragraph tag with a class of error.

Written by Philip Norton.

JQuery Image Switcher

7 December, 2009 | JQuery | No comments

Using something like CrossSlide is fine if you want fancy effects in your image translations, but for more simple effects you can use a single function to simply swap one image for another. First, lets create some simple markup that will allow us to display some images.

<div class="slideshow"> <img src="image1.png" alt="Image 1" /> <img src="image2.png" alt="Image 2" /> <img src="image3.png" alt="Image 3" /> <img src="image4.png" alt="Image 4" /> </div> (more...)

Written by Philip Norton.

How To Check And Uncheck A Checkbox With jQuery

27 July, 2009 | JQuery | No comments

To check and uncheck a checkbox using jQuery you first need to access the checkbox element using the $() function. Once you have done that you can retrieve or change the value of the checkbox quite easily.

To uncheck a checkbox use the following snippet, which makes nice use of the jQuery attribute filters:

$('input[name=mycheckbox]').attr('checked', false);

To check a checkbox use the following:

$('input[name=mycheckbox]').attr('checked', true); To test if a checkbox is set or not use one of the following, both return true if checked and false is unchecked. var checked = $('input[name=mycheckbox]').is(':checked'); var checked = $('input[name=mycheckbox]').attr('checked');

Written by Philip Norton.

JQuery Timepicker Plugin

12 April, 2009 | JQuery | No comments

I had the need to create a time selecting component for a form, but I didn't want to have lots of extra components. After a little bit of searching about I found the following JQuery UI plugin called timepicker.

This plugin will take a input box as the argument and will add three selection boxes for hours, minutes and seconds. It will then hide the original input box.

However, there were two thing that I needed that this plugin didn't do. The first is that it was in a 12 hour format and the second is that the plugin didn't have a second selection. So I decided to adapt that plugin in order to incorporate these things.

Here is the modified plugin.

(function($){     jQuery.fn.timepicker = function(){         this.each(function(){             // get the ID and value of the current element             var i = this.id;             var v = $(this).val();               // the options we need to generate             var hrs = new Array('00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23');             var mins = new Array('00','05','10','15','20','25','30','35','40','45','50','55');             var secs = new Array('00','05','10','15','20','25','30','35','40','45','50','55');               // default to the current time             var d = new Date;             var h = d.getHours();             var m = d.getMinutes();             var s = d.getSeconds();                          // override with current values if applicable             // round the minutes and seconds to nearest 10             if(v.length == 8){                 h = parseInt(v.substr(0,2));                 x = parseInt(v.substr(3,2));                 m = (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;                 x = parseInt(v.substr(6,2));                 s = (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;                             }                  // build the new DOM objects             var output = '';                          output += '<select id="h_' + i + '" class="h timepicker">';                             for(hr in hrs){                 output += '<option value="' + hrs[hr] + '"';                 if(parseInt(hrs[hr]) == h) output += ' selected';                 output += '>' + hrs[hr] + '</option>';             }             output += '</select>';                  output += '<select id="m_' + i + '" class="m timepicker">';                             for(mn in mins){                 output += '<option value="' + mins[mn] + '"';                 if(parseInt(mins[mn]) == m) output += ' selected';                 output += '>' + mins[mn] + '</option>';             }             output += '</select>';                                  output += '<select id="s_' + i + '" class="p timepicker">';                             for(ss in secs){                 output += '<option value="' + secs[ss] + '"';                 if(secs[ss] == s) output += ' selected';                 output += '>' + secs[ss] + '</option>';             }             output += '</select>';                                  // hide original input and append new replacement inputs             $(this).css('display','none');             $(this).after(output);         });                  $('select.timepicker').change(function(){             var i = this.id.substr(2);             var h = $('#h_' + i).val();             var m = $('#m_' + i).val();             var s = $('#s_' + i).val();             var v = h + ':' + m + ':' + s;             $('#' + i).val(v);         });                  return this;     }; })(jQuery);

You can view and download this code here.

The plugin will also update itself with the time that is present in the text field, as long as it matches the format HH:MM:SS.

I have also setup a test page for this JQuery timeplugin.

You can run the plugin by using the following code:

$('#timepicker').timepicker();

Written by Philip Norton.