Search code examples
javascriptjquerykeypress

Change word on each keypress javascript/jquery


I'm new to javascript/jquery and stuck with the following problem:

I want to the value of my HTML paragraph element "abc" to change when either 'a' or 'l' is pressed.

The code works but does so only once. My aim is to change the "abc" element, say, 20 times whereby each time one element from "newwords" is picked.

Maybe I forgot a loop somewhere?

html:

<p id="abc" style="font-size:20px" align="center">WORD</p>  

javascript/jquery:

var newwords = ["NEWWORD1", "NEWWORD2", "NEWWORD3"];
var rand_new = newwords[Math.floor(Math.random() * newwords.length)];

$(function(){
    $(document).keypress(function(e){
        if ($(e.target).is('input, textarea')) {
            return;
        };
        if (e.which === 97 || e.which === 108) {
            document.getElementById("abc").firstChild.nodeValue = rand_new;
        };
        });
    });

Solution

  • It's not that your code only works once, your problem is that you only generate the random number once, so you always get the same result. Move the number generation inside the function and it works:

    var newwords = ["NEWWORD1", "NEWWORD2", "NEWWORD3"];
    
    $(document).keypress(function(e){
        if ($(e.target).is('input, textarea')) {
            return;
        };
        var rand_new = newwords[Math.floor(Math.random() * newwords.length)];
        if (e.which === 97 || e.which === 108) {
            document.getElementById("abc").firstChild.nodeValue = rand_new;
        };    
    });
    

    jsfiddle: http://jsfiddle.net/R5vqM/1/