Detecting keypresses cross-browser using jquery

Date: 26th February 2009 at 8:36 pm | Filed under: development, scripts | Author: Sam Burdge | Tags: , , ,

Using keypresses as an alternate way to to navigate through websites  is a great way to make sites more accessible. For instance pressing 'p' takes the user to the previous page, while pressing 'n' takes them to the next. The benefits of using jQuery to achieve this are:

  1. Concise code
  2. Easy to implement various functions on keypress
  3. Works on IE, Firefox & Safari

DETECTING THE KEY CODE

To detect which key a user has pressed you need to set up a function that returns an ascii code each time a key is pressed. A full table of ascii codes is available here. The tricky part to this is that Mozilla and Safari define the value as charCode, while IE defines  it as keyCode. The following script is based on the 'n' key and 'p' key, it takes the links from the 'Previous' and 'Next' buttons on your site and changes page when the key is pressed. Also note that it is important to detect for both the lower-case and upper-case letter as the ascii codes will be different for each.

SOURCE

//process this function whenever a key is pressed
$(document).keypress(function (e) {
//Next
//if the keyCode or charCode is 110 (lower case n) or 78 (upper case N)
if (e.keyCode == 110 || e.charCode == 110 || e.keyCode == 78 || e.charCode == 78){
//grab the href attribute from the link with the id "next_link"
var next_link = $("a#next_link").attr("href");
//if the next link exists (i.e if it's not the last page)
if(next_link){
//go to the next page
window.location = next_link;
}
}
//Previous
//works exactly as the above example but for the 'p' and 'P' keys
if (e.keyCode == 112 || e.charCode == 112 || e.keyCode == 80 || e.charCode == 80){
var prev_link = $("a#prev_link").attr("href");
if(prev_link){
window.location = prev_link;
}
}

});

You must have the jQuery library installed on your site to run this script. For more info about jquery visit the site: http://jquery.com/

7 Responses to “Detecting keypresses cross-browser using jquery”

  • Comment by Steve Holden
    Date: June 26th, 2009 at 4:03 pm

    What happens when the page contains a form and the user types into the form inputs?

  • Comment by Sam Burdge
    Date: June 26th, 2009 at 4:27 pm

    Hi Steve
    Good question. I hadn’t tested that.
    You could always try working around this by using the focus() and blur() events for the form input to switch the keypress function on or off.

    Basic example:

    $(’input’).focus(function(){
    var keypress_active = false;
    });
    $(’input’).blur(function(){
    var keypress_active = true;
    });

  • Comment by lionel
    Date: October 8th, 2009 at 9:39 pm

    Hi, thanks for the infos, the code is working well, but is it possible to replace the windows.location by an ajax call ? thanks ?

  • Comment by lionel
    Date: October 8th, 2009 at 9:40 pm

    if yes how ? ;) thanks

  • Comment by links for 2010-03-13 | Folks Pants
    Date: April 8th, 2010 at 5:22 pm

    [...] Detecting keypresses cross-browser using jquery | Sam Burdge (tags: jquery keypress) [...]

  • Comment by Jason Cramer
    Date: March 15th, 2011 at 11:58 pm

    BRILLIANT! This was exactly what I had been looking for. Love the color scheme to your site too. Very retro DOS-ish.

  • Comment by Rachel Nabors
    Date: March 17th, 2011 at 1:49 pm

    Hello Sam! This is exactly what I am looking for for arrow-key navigation through my comics site. I need to disable it when people are typing in comment fields, though, and I just can’t seem to implement your example code for disabling above.

    Could you expand on it a bit? It would be a great help if you could!

Leave a Comment

A Single html Form With Multiple Submit Buttons - Changing a Form’s Action Attribute using jQuery

Date: 15th February 2009 at 4:48 pm | Filed under: development, scripts | Author: Sam Burdge | Tags: , , , , , ,

I was recently confronted with the problem of having a single html form with three different submit buttons, each button submitting the form data to a different php script. This is obviously impossible with html alone, as a form can only have one 'action' attribute, which dictates the URL of the file that the form's data is submitted to.

I searched around on the web for an easy way to implement this and found various examples. One of the best examples I found was on CoderLab's blog: Multiple submit buttons on a multiple blog which uses javascript to apply a different action attribute to the form depending on which button is pressed. Each button in the form has it's own onClick function like so:

<form name="myForm" id="myForm">
Search: <input type="text" id="wrdSearch"/>
<input type="button" name="google" id="google" value="Google" onClick="SendTo(this.id)"/>
<input type="button" name="msn" id="msn" value="MSN" onClick="SendTo(this.id)"/>
<input type="button" name="yahoo" id="yahoo" value="Yahoo" onClick="SendTo(this.id)"/>
</form>

(Visit the page to see the javascript that goes with it: http://blog.coderlab.us/2005/10/04/multiple-submit-buttons-in-a-form/)

As I already had jQuery installed on the site, and the CoderLab script would still need some modification to serve my specific purpose, I decided to see if I could find a simpler way to achieve a similar result using jQuery. The form on my site was a lot more complex, with many fields etc. So what I really needed was a script that would submit all the form data to each of the 3 php scripts depending on which submit button was clicked.

Firstly, I stripped the onClick functions out of the form and removed the name attributes from the buttons too, like so:

<form id="myForm" method="post">
Search: <input type="text" name="search"/>
<input type="button" id="button1" value="Submit to script 1" />
<input type="button" id="button2" value="Submit to script 2" />
<input type="button" id="button3" value="Submit to script 3" />
</form>

I then wrote the following jQuery script to change the form's action attribute accordingly and submit it when each button is pressed:

$(document).ready(function(){

$("#button1").click(function(){
$('form#myForm').attr({action: "script_1.php"});
$('form#myForm').submit();
});

$("#button2").click(function(){
$('form#myForm').attr({action: "script_2.php"});
$('form#myForm').submit();
});

$("#button3").click(function(){
$('form#myForm').attr({action: "script_3.php"});
$('form#myForm').submit();
});

});

The script should work on any browser that is compatible with jQuery (see here: http://docs.jquery.com/Browser_Compatibility)

For more information on installing and using jQuery visit the website: http://jquery.com/

10 Responses to “A Single html Form With Multiple Submit Buttons - Changing a Form’s Action Attribute using jQuery”

  • Comment by A Single html Form With Multiple Submit Buttons - Changing a Form’s Action Attribute using jQuery - PHP-update.co.uk
    Date: March 11th, 2009 at 1:55 pm

    [...] More here: A Single html Form With Multiple Submit Buttons - Changing a Form’s Action Attribute controlling j… [...]

  • Comment by Dickram
    Date: March 16th, 2009 at 6:33 pm

    You rock man. I was just looking for this and found your site. I’m using jquery too, with code igniter.
    Thank you very much!!

  • Comment by David
    Date: September 24th, 2010 at 1:04 am

    Hey, your article gives me a big help. Why using $(’form#myForm’) rather than $(’#myform’) though?? thank you very much

  • Comment by Sam Burdge
    Date: September 24th, 2010 at 1:17 am

    Hi David
    Glad it helped ;)

    there is no difference between using $(’form#myForm’) or $(’#myform’)

    i just wrote it that way as i thought it would make it clearer for the tutorial.

  • Comment by David
    Date: September 24th, 2010 at 4:25 am

    Thank you for your reply!~many thanks mate

  • Comment by Ben
    Date: October 4th, 2010 at 10:12 am

    Brilliant, cheers mate. Really helped me out of a whole

  • Comment by Ben
    Date: October 4th, 2010 at 10:13 am

    that should have said a whole world of frustration!!

    (pressed enter a little early)

  • Comment by Tom Lackey
    Date: April 27th, 2011 at 9:21 pm

    this served me well, thanks!

  • Comment by Vishal
    Date: June 10th, 2011 at 9:50 am

    Wow….great stuff… really helped a lot.. thanx buddy.

  • Comment by Mr. Serra
    Date: June 17th, 2011 at 2:57 pm

    God save the internet and people like you!
    Thank you very much!!

Leave a Comment

Comus Productions Website Update

Date: 23rd January 2009 at 1:43 am | Filed under: blog, portfolio | Author: Sam Burdge | Tags: , , ,

Comus Website ScreenshotComus Website ScreenshotComus Website ScreenshotComus Website Screenshot

The Comus Productions website has recently undergone a major upgrade. It now has loads of new Flash presentations which incorporate a new set of Comus stings and idents.

The site is now fully content managed with the Admin76 content management system by 76 Creative, so all the text, images and video content on the site can be easily updated by the site's owner.

I used the javascript jQuery library a lot throughout the site, to fade text in and out, fade images and to switch slideshows and videos too.

A prominent feature of the site is the recreation of the Photoshop Lens Flare as an animated flash movie, which I adapted from this lensflare project on FlashDen. It was this lensflare that inspired the most experimental flash movie of the site - the Comus Viewfinder which can be seen on the links page.

Other Flash features include a more corporate style flash presentation on the services page and an explosive ident on the home page!

Visit the site: www.comusproductions.co.uk

Leave a Comment