0

I want to detect when user presses Delete key and I found the tutorial here

The code works great in jsfiddle.net, this is the link- http://jsfiddle.net. I copied the same code to my computer, and then I tested it but it didn't work up to the mark.

I am posting my code here:

<html>

<script src="./jquery-1.10.2.min.js"></script> 


<body>
<script language="javascript" type="text/javascript">

var specialChars = {
            27: "esc", 9: "tab", 32: "space", 13: "return", 8: "backspace", 145: "scroll", 20: "capslock", 144: "numlock",
            19: "pause", 45: "insert", 36: "home", 46: "del", 35: "end", 33: "pageup", 34: "pagedown",
            37: "left", 38: "up", 39: "right", 40: "down", 109: "-",
            112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6",
            118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12", 191: "/"
        };

function chromeKeyPress(i,e){
    e.type="chromekeypress";
    e.which = 0;
    handleKey(e);
}
function handleKey(e) {
    $("#r").html($("#r").html() + "\n" +
        e.type + "\n" +
        "  which: " + e.which + " == " + String.fromCharCode(e.which) + "\n" +
        "  keyCode: " + e.keyCode + " == " + String.fromCharCode(e.keyCode) + "\n" +
     "");
}

$("textarea").keydown(function(e) {
    if (specialChars[e.keyCode])
    {
        $("textarea").trigger("chromekeypress", e);

        $("textarea").unbind("keypress");
        setTimeout(function(){ $("textarea").bind("keypress", handleKey); },10);
    }
});
$("textarea").keypress(handleKey);
$("textarea").bind("chromekeypress", chromeKeyPress);

</script>


<textarea></textarea>

<pre id="r"></pre>


</body>
</html>                                                                            

I linked the jquery, jquery-1.10.2.min.js. what is wrong in my code for the javascript.

2 Answers 2

3

You can wrap your code inside DOM ready handler $(document).ready(function() {....}); or shorter form $(function) {...}); to make sure all of your DOM elements has been loaded properly before executing your jQuery code:

$(function() {
    // Your jQuery code here
});

Your code works on jsFiddle because the above task has been done automatically when you've included jQuery from jsFiddle

0
0

put your code inside ready event

$( document ).ready(function() {
    // Handler for .ready() called.
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.