00:00
00:00
Newgrounds Background Image Theme

Chan99 just joined the crew!

We need you on the team, too.

Support Newgrounds and get tons of perks for just $2.99!

Create a Free Account and then..

Become a Supporter!

Detect clicks in JavaScript - best?

1,238 Views | 14 Replies
New Topic Respond to this Topic

I am looking for the best way of detecting if someone clicked (like) enter, a, s and make something happen (or just any key).

So, what would the best, most modern, coolest, nicest, smallest way of doing this?

Response to Detect clicks in JavaScript - best? 2012-07-24 19:39:11


At 7/24/12 06:34 PM, uglybetty wrote: So, what would the best, most modern, coolest, nicest, smallest way of doing this?

Well that excludes vanilla JavaScript, so here's how you can do that with jQuery:

HTML

<button id="my-button">click me</button><br>
<textarea id="my-text"></textarea>

JavaScript

jQuery(document).ready(function($){
    $("#my-button").on("click", function(){
        console.log("You clicked the button with id 'my-button'!");
    });

    $("#my-text").on("keydown", function(event){
        console.log("You pressed the key with ASCII value '" + event.which + "'");
    });
});

There are plenty of tutorials available here.
And the documentation for jQuery is very thorough.

How much experience do you have with writing JavaScript though?
If you don't know it I recommend learning vanilla JS before learning jQuery (or any other framework).

Response to Detect clicks in JavaScript - best? 2012-07-25 10:20:27


At 7/24/12 07:39 PM, Diki wrote:
At 7/24/12 06:34 PM, uglybetty wrote: So, what would the best, most modern, coolest, nicest, smallest way of doing this?
Well that excludes vanilla JavaScript, so here's how you can do that with jQuery:

HTML

<button id="my-button">click me</button><br>
<textarea id="my-text"></textarea>

JavaScript

jQuery(document).ready(function($){
$("#my-button").on("click", function(){
console.log("You clicked the button with id 'my-button'!");
});

$("#my-text").on("keydown", function(event){
console.log("You pressed the key with ASCII value '" + event.which + "'");
});
});

There are plenty of tutorials available here.
And the documentation for jQuery is very thorough.

How much experience do you have with writing JavaScript though?
If you don't know it I recommend learning vanilla JS before learning jQuery (or any other framework).

That is indeed a good code you have there. The problem is that I do not want to use a framework because I am not using it from before. I am not a fan of using the whole library for just one function. Also, I have never used jQuery before.

I like to make my own code (vanilla JS) because it is much better to maintain and understand exactly what I am doing!

So, what I have now is this:

<body onload="document.body.focus();" onkeyup="return keypressed(event)">
When the key is up it calls this function in JavaScript:

function keypressed(e) {
    var intKey = (window.Event) ? e.which : e.keyCode;
    if (intKey == 13) { // 13 = enter key
        //something happens if the key is clicked
    }
        // here, you can add as many if sentences for key strokes as you want! (same as first)

return true;
}

Response to Detect clicks in JavaScript - best? 2012-07-25 11:27:00


At 7/25/12 10:20 AM, uglybetty wrote: That is indeed a good code you have there. The problem is that I do not want to use a framework because I am not using it from before. I am not a fan of using the whole library for just one function.

That example code I gave is you is using far more than just one jQuery function.
But anyways, since you're still learning JavaScript it's a good idea for you to stay away from jQuery for now.

At 7/25/12 10:20 AM, uglybetty wrote: I like to make my own code (vanilla JS) because it is much better to maintain and understand exactly what I am doing!

It's actually far more difficult to maintain, as jQuery, or other frameworks such as MooTools, are standards compliant and cross-browser compatible out of the box, your own vanilla code will not be. But that's fine for now; you're still learning JS so you don't need to worry about writing perfect code; just worry about learning.

At 7/25/12 10:20 AM, uglybetty wrote: So, what I have now is this:

<body onload="document.body.focus();" onkeyup="return keypressed(event)">
When the key is up it calls this function in JavaScript:

function keypressed(e) {
var intKey = (window.Event) ? e.which : e.keyCode;
if (intKey == 13) { // 13 = enter key
//something happens if the key is clicked
}
// here, you can add as many if sentences for key strokes as you want! (same as first)

return true;
}

You shouldn't use onload="" in the body element; it's slow, and is mixing your HTML and JavaScript (which makes your code obfuscated and creates redundant dependencies). Whenever possible avoid using any inline events with HTML, such as onload or onkeyup (or any others).

Note:
For the sake of brevity I'm not including code that will work in older browsers.
The code I'm posting will require a modern browser.

Your best bet is to use an event listener:

function onDOMLoaded() {
    document.removeEventListener("DOMContentLoaded", onDOMLoaded, false);
    alert("DOM Loaded");
}

document.addEventListener("DOMContentLoaded", onDOMLoaded, false);

Run it on jsfiddle.

That will keep your logic entirely inside JavaScript and not in your HTML.

What this is doing is waiting for the Document Object Module, or DOM for short, to load. The DOM is basically a tree of your HTML; it allows you to treat the HTML you wrote as objects.
Anytime you want to do anything to your page, you need to wait for the DOM to load.

Capturing key presses can also be done using an event listener:

function onKeyPress(event) {
    if (event.which == 13) {
        // enter key
    }
}

document.addEventListener("keypress", onKeyPress, false);

Here is an article that goes into pretty thorough depth regarding events and event listeners.

Response to Detect clicks in JavaScript - best? 2012-07-25 13:59:15


At 7/25/12 11:27 AM, Diki wrote: jQuery

seconded, jQuery is a god send for things like this.

Response to Detect clicks in JavaScript - best? 2012-07-25 18:39:43


That is indeed a good code you have there. The problem is that I do not want to use a framework because I am not using it from before. I am not a fan of using the whole library for just one function.
That example code I gave is you is using far more than just one jQuery function.
But anyways, since you're still learning JavaScript it's a good idea for you to stay away from jQuery for now.

I know, but not like a function in JavaScript - in literal meaning of functioning a button press. Can I use void/sub in JavaScript instead of function?

I like to make my own code (vanilla JS) because it is much better to maintain and understand exactly what I am doing!
It's actually far more difficult to maintain, as jQuery, or other frameworks such as MooTools, are standards compliant and cross-browser compatible out of the box, your own vanilla code will not be. But that's fine for now; you're still learning JS so you don't need to worry about writing perfect code; just worry about learning.

My grandmother always makes the food ground up. I took it to my senses and always do it in JavaScript.

You shouldn't use onload="" in the body element; it's slow, and is mixing your HTML and JavaScript (which makes your code obfuscated and creates redundant dependencies). Whenever possible avoid using any inline events with HTML, such as onload or onkeyup (or any others).

Oh ok! On my site I have this onload. Whenever I open it by clicking enter (since I have a really fast site and a light one) my JavaScript runs. The problem is that the JavaScript is not loaded, it says "undefined". Should I have a delay?

Note:
For the sake of brevity I'm not including code that will work in older browsers.
The code I'm posting will require a modern browser.

I can sure add some to the older ones and some to the newer ones.

Your best bet is to use an event listener:

function onDOMLoaded() {
document.removeEventListener("DOMContentLoaded", onDOMLoaded, false);
alert("DOM Loaded");
}

document.addEventListener("DOMContentLoaded", onDOMLoaded, false);

Run it on jsfiddle.

That will keep your logic entirely inside JavaScript and not in your HTML.

That actually is really nice. I love it, but the problem is that older browser do not support it. Maybe on window load?

What this is doing is waiting for the Document Object Module, or DOM for short, to load. The DOM is basically a tree of your HTML; it allows you to treat the HTML you wrote as objects.
Anytime you want to do anything to your page, you need to wait for the DOM to load.

Capturing key presses can also be done using an event listener:

function onKeyPress(event) {
if (event.which == 13) {
// enter key
}
}

document.addEventListener("keypress", onKeyPress, false);

Here is an article that goes into pretty thorough depth regarding events and event listeners.

That code looks more maintainable. The question is: will it work in Fire Fox?

The code:

var intKey = (window.Event) ? e.which : e.keyCode;

was made to make it work in Firefox.

Response to Detect clicks in JavaScript - best? 2012-07-26 14:16:23


function onKeyPress(event) { 
if (event.which == 13) { 
// enter key 
} 
} 

document.onkeypress = keyPressHandlerFunction;

This is what I have now. What next?

Response to Detect clicks in JavaScript - best? 2012-07-26 14:18:47


SORRY FOR TRIPLE POST... HERE'S THE RIGHT CODE!

function keypressed(event) { 
if (event.which == 13) { 
// enter key 
} 
} 

document.onkeypress = keypressed;

Response to Detect clicks in JavaScript - best? 2012-07-26 15:43:17


At 7/25/12 06:39 PM, uglybetty wrote: Oh ok! On my site I have this onload. Whenever I open it by clicking enter (since I have a really fast site and a light one) my JavaScript runs. The problem is that the JavaScript is not loaded, it says "undefined". Should I have a delay?

What doesn't load?
What says "undefined"?

At 7/25/12 06:39 PM, uglybetty wrote: That actually is really nice. I love it, but the problem is that older browser do not support it. Maybe on window load?

To support legacy browsers, such as IE6 or IE7, you would need to do something like this:

Note: This code is by no means an efficient solution; it's just an example.

/* * * Listener Functions * * */

var __DOM_LOADED = false;

function onDOMContentLoaded() {
    if (typeof document.addEventListener !== "undefined") {
        document.removeEventListener("DOMContentLoaded", onDOMContentLoaded, false);
        if (!__DOM_LOADED) {
            __DOM_LOADED = true;
            onReady();
        }
    } else if (typeof document.attachEvent !== "undefined" && document.readyState === "complete" && document.body !== null) {
        if (!__DOM_LOADED) {
            __DOM_LOADED = true;
            onReady();
        }
    }
}

function onReady() {
    alert("DOM is ready!");
}

/* * * Add Listeners * * */

if (typeof document.addEventListener !== "undefined") {
    document.addEventListener("DOMContentLoaded", onDOMContentLoaded, false);
    window.addEventListener("load", onDOMContentLoaded, false);
} else if (typeof document.attachEvent !== "undefined") {
    document.attachEvent("onreadystatechange", onDOMContentLoaded);
    window.attachEvent("onload", onDOMContentLoaded, false);
} else {
    window.onload = onReady;
}

Run it on jsfiddle.
Is based on this section of jQuery.

That gigantic blog is why I kept it out of my original post, because it's not necessary.
If you need to support legacy browsers then you should use a framework to handle that for you, and if you're still learning JavaScript then you don't need to worry about supporting legacy browsers right now.

At 7/25/12 06:39 PM, uglybetty wrote: That code looks more maintainable. The question is: will it work in Fire Fox?

Yes. All of the code I've posted works in Firefox.
Generally speaking you will only run into issues Internet Explorer.

Response to Detect clicks in JavaScript - best? 2012-07-26 15:47:03


At 7/26/12 02:16 PM, uglybetty wrote: This is what I have now. What next?

What are you trying to do?

Response to Detect clicks in JavaScript - best? 2012-07-26 15:59:21


At 7/26/12 03:47 PM, Diki wrote:
At 7/26/12 02:16 PM, uglybetty wrote: This is what I have now. What next?
What are you trying to do?

In my web app I need a code that does something when the user click the keyboard button (example) enter + other keys.

Response to Detect clicks in JavaScript - best? 2012-07-26 16:02:30


At 7/26/12 03:59 PM, uglybetty wrote: In my web app I need a code that does something when the user click the keyboard button (example) enter + other keys.

I already posted code to detect when a key is pressed, and linked you to a jsfiddle of it running.

What are you trying to make happen when the key is pressed?
Are you trying to detect when multiple keys have been pressed at once?

You need to be more specific.

Response to Detect clicks in JavaScript - best? 2012-07-26 16:07:27


At 7/26/12 04:02 PM, Diki wrote:
At 7/26/12 03:59 PM, uglybetty wrote: In my web app I need a code that does something when the user click the keyboard button (example) enter + other keys.
I already posted code to detect when a key is pressed, and linked you to a jsfiddle of it running.

What are you trying to make happen when the key is pressed?
Are you trying to detect when multiple keys have been pressed at once?

You need to be more specific.

When user has clicked enter, a, s, z, x or c a something happens. Not at once, but multiple keys (enter,a,s,z,x,c)

Response to Detect clicks in JavaScript - best? 2012-07-26 16:24:46


If you want to detect key combos, and do it using vanilla JavaScript, then your code is going to be pretty verbose.
I slapped together a prototype here:

var __element;
var __keysdown = {};

function onDOMLoaded() {
    document.removeEventListener("DOMContentLoaded", onDOMLoaded, false);
    document.addEventListener("keydown", onKeyDown, false);
    document.addEventListener("keyup", onKeyUp, false);
}

function onKeyDown(event) {
    __keysdown[event.which] = true;
    
    if (isPressing([13,65])) {
        alert("You're pressing 'ENTER' and 'A'");
    }
}

function onKeyUp(event) {
    delete __keysdown[event.which];
}

function isPressing(keys) {
    for (var i = 0; i < keys.length; i++) {
        if (typeof __keysdown[keys[i]] === "undefined") {
            return false;
        }
    }
    return true;
}

document.addEventListener("DOMContentLoaded", onDOMLoaded, false);

Run it on jsfiddle.

If you use the jsfiddle version make sure the "result" window on the right has focus.
Pressing "ENTER" and "A" at the same time should trigger an alert.

Basically you need to record each key that is pressed, and each time a key is released, remove that key from the record.
That way your object/array/whatever will only contain keys that are currently pressed. To check if a combo is being pressed you simply need to check for the existence of each key, which is what this function does:

function isPressing(keys) {
    for (var i = 0; i < keys.length; i++) {
        if (typeof __keysdown[keys[i]] === "undefined") {
            return false;
        }
    }
    return true;
}

Note: If you pass this function bad data then it will return true and possibly produce erroneous behavior; it's only a prototype, afterall.

Response to Detect clicks in JavaScript - best? 2012-07-26 16:31:57


Thanks for the help Diki. I sent you a message just in case, but that's OK. Thank you for all the help!