Click and keypress combined

Hey guys I'm trying to make combine click and keypress on my function, but nothing I've tried so far seems to work. This is my code:

function victoryMessage() {

    $(document).off("keyup", handleKeyUp);
    $('#feedback').append("Bravo!<br><br><div id='replay' class='button'>Nastavi</div>");


    $('#replay').on("click",function () {
        if(questionBank.length>3) {
            gameScreen();
        }
        else {
            finalPage();
        }
    });

    $(document).off("tap", keepFocus).trigger("tap");
}

so far I have tried following:

$("#replay").on("click keyup", function (e) {
    if (e.type == "click" || e.keyCode == 13) {
        if(questionBank.length>0) {
            gameScreen();
        }
        else {
            finalPage();
        }
    }
});

and

var callback = function() {
    if(questionBank.length>0) {
        gameScreen();
    }
    else {
        finalPage();
    }   
};

$("#replay").keypress(function() {
    if (event.which == 13) callback();
});

$('#replay').click(callback);

and

$(document).on("keypress", function(e){
    if (e.which == 13) {
        testKey();
    }
});

I have also tried some other things, but nothing seems to work. Here the link so you see my full code in action http://www.wpacademy.nextweb.space/TestingMobile/
EDIT: To clarify as Andy said I want the click to register when clicking only the the replay button, and the enter key to register when pressed anywhere within the document.

Answers 1

  • Since the element is created via JS, assign the click handler to document and defer it to #replay. And I'm not sure how you plan on capturing keyup on a div, but if you set contenteditable on the div, you can double click on the text, then type in it to show both events are being captured. Here's a codepen http://codepen.io/anon/pen/RpGEWK

    $('#feedback').append("Bravo!<br><br><div id='replay' class='button' contenteditable>Nastavi</div>");
    $(document).on("click keyup", "#replay", function(e) {
      console.log(e);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="feedback"></div>


Related Articles