Search code examples
jqueryhtmltwitter-bootstrapkeypressenter

Bootstrap button keypress not working for 'Enter' key


So I'm building a website that randomly prints quotes from an array when a button is pressed. It is working right now when one presses the button using their mouse. However, I've added code to listen for the 'Enter' key to click said button, and it is not working. I've been playing with my code for quite some time today, and I still cannot get it to work. Here is my code right now:

JQuery:

$(document).ready(function(){
 var quotes = ['"A dream does not become reality through magic; it takes sweat, determination, and hard work." - Colin Powell', 
'"Success is the result of perfection, hard work, learning from failure, loyalty, and persistence." - Colin Powell', 
'"Nothing ever comes to one, that is worth having, except as a result of hard work." - Booker T. Washington', 
'"I learned the value of hard work by working hard" - Margaret Mead', 
'"Out work everyone. If you are working harder than everybody, then what are you worrying about?" - John Sonmez', 
'"Those dreams that you have, those goals that you have, do not put them off another second. Get on them. Go out and make them happen starting right now" - Jocko Willink', 
'"Go to bed tired." - Tim Kennedy', 
'"Do that thing that you dont know if you can do. Stop being afraid of hard work." - Tim Kennedy', 
'"Discipline equals freedom. The more discipline you have, the harder you work, the more effort you put into it, the more freedom you are going to have." - Jocko Willink',
'"Dont think about it, start doing it." - Anonymous'];

var rand = quotes[Math.floor( Math.random() * quotes.length )];
 $('blockquote').text(rand); 

//On Button Click 
$('#newQuote').click(function(){
  $('blockquote').text(quotes[Math.floor(Math.random() * quotes.length)]);
});

//Listen for Enter Key
$('blockquote').keyup(function(event){
if(event.keyCode == 13){
    $('#newQuote').click();
    $('blockquote').text(quotes[Math.floor(Math.random() * quotes.length)]);
 }

  });
});

And my HTML:

<a id ="newQuote" class="btn btn-primary btn-lg">New Quote</a>

Also here is the site on codepen: http://codepen.io/codyreandeau/pen/VmzWXG


Solution

  • i think you need to change your keydown listener into this

    
        $('#newQuote').keyup(function(event){
        if(event.keyCode == 13){
            $('blockquote').text(quotes[Math.floor( Math.random() * quotes.length )]);
        }
        });
    
    

    and your button into this

    <button id="newQuote" class="btn btn-primary btn-lg">New Quote</button>