Jump to content

Recommended Posts

You just need to attach the events (click on the buttons, and keyup on the document) to call the same function which performs the animation:

 

$(document).ready(function() {

    // Assign the left/right button click events
    $('#leftButton').click(moveLeft);
    $('#rightButton').click(moveRight);

    // Assign the key press event to the document
    $(document).keyup(function(event) {
        // IE doesn't support event.which
        if (event.which == null) {
            var key = event.keyCode;
        } else {
            var key = event.which;
        }

        // 37 = left arrow
        if (key == 37) {
            moveLeft();
        // 39 = right arrow
        } else if (key == 39) {
            moveRight();
        }

        // Prevent normal event action (possible scrolling
        // if there's a horizontal scroll bar)
        event.preventDefault();
    });

});

function moveLeft() {
    alert('moving left...');
}

function moveRight() {
    alert('moving right...');
}

 

That will event work with IE6!

 

Note I used the "keyup" event instead of "keypress" by the way, which is because certain keys are only supported in certain events. Working with key detection is quite a nightmare sometimes in JavaScript! Also for that to work you would need to assign the left/right buttons an ID of "leftButton" and "rightButton" - but obviously you change those.

Just tested this in FF4 and found an issue. It's caused by the alert() call in the moveLeft() and moveRight() functions, taking focus from the document so that you have to click on the page before the event will trigger again. When you actually add the proper animation code without an alert() call though, that won't be a problem.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.