Robert Rocha Robert Rocha - 3 months ago 15x
jQuery Question

jQuery return false not stopping scrolling on keydown

Sample HTML response from server after input:

<ul class="datalistPlaceholder hidden" style="display: block;">
<li><a class="tag" href="#">#<span style="font-weight: bold">ar</span>igato</a></li>
<li><a class="tag" href="#">#<span style="font-weight: bold">ar</span>izona</a></li>
<li><a class="tag" href="#">#cle<span style="font-weight: bold">ar</span>water</a></li>


$('#search-field').keyup(function(e) {, e);

function ajaxAutocomplete(e) {
var hash_tag = $.trim($(this).val());

url : 'autocomplete.php',
method : 'GET',
dataType: 'html',
data : {tag : hash_tag}
.done(function(response) {
if (response) {

if (e.keyCode === 40) { // down key
$('.tag').keydown(function(e) {, e);
} else if (e.keyCode === 38) { // up key
} else {
.fail(function() {
alert('Something went wrong');

function down(e)
if (e.keyCode === 40) {
// stops page from scrolling
return false;

When the user uses the down arrow key to select an option from the drop down menu the page scrolls. I thought returning false would prevent this. What am I doing wrong?


This is happening because you have this:

$('.tag').keydown(function(e) {, e);

Not sure why you are doing it that way instead of just using down directly but you aren't returning whatever down() returns so your anonymous callback function will be returning undefined instead of false

Either use down directly as the callback function or do the extra return

$('.tag').keydown(function(e) {

Note you could also call e.preventDefault() instead of returning false to prevent default actions.

As a side note doing $('.tag').keydown(function(e)... everytime in your done callback is going to keep adding new event handlers for those elements that might not get destroyed by $('.datalistPlaceholder').html(response). You can use a delegated event so that you only have to create the handler once: