George Reith
George Reith

Reputation: 13476

Triggering same function on both click and keypress

I have the following function which fires when clicked but how would I also make it fire on enter without creating a new function? (if possible).

$("#jump_menu select option").click(function(){
    var hash = $(this).val();
    var target_offset = $(hash).offset();
    $('html, body').animate({scrollTop:target_offset.top}, 500);
})  

Upvotes: 1

Views: 2353

Answers (4)

Sheik797
Sheik797

Reputation: 535

$(selector).on('keyup , change' ,function() {
--- Do some thing ---
});

Upvotes: 0

sje397
sje397

Reputation: 41862

Try binding to

$("#jump_menu select").change

...instead.

Alternatively just move it to a standalone function and bind to what you need:

function handler(elem) {
    var hash = $(elem).val();
    var target_offset = $(hash).offset();
    $('html, body').animate({scrollTop:target_offset.top}, 500);
}

$('#jump_menu select option').click(handler);
$('#jump_menu select').change(handler);

You may need to save and compare event timestamps though to ensure you don't call your handler twice for a single selection.

Upvotes: 4

defuz
defuz

Reputation: 27621

function runAnimate() {
    var hash = $(this).val();
    var target_offset = $(hash).offset();
    $('html, body').animate({scrollTop:target_offset.top}, 500);
}

$("#jump_menu select option").click(runAnimate);  

$('body').change(runAnimate);

Upvotes: 0

Lennard Fonteijn
Lennard Fonteijn

Reputation: 2651

You have to globally declare your function, rather than declaring it in your .click function like so:

function animateBody() {
    var hash = $(this).val();
    var target_offset = $(hash).offset();
    $('html, body').animate({scrollTop:target_offset.top}, 500);
}

After that, you can bind the function to multiple event without redeclaring it twice:

$("#jump_menu select option").click(animateBody);
$("#jump_menu select").change(animateBody);

The resulting could look something like this:

//Other JQuery/Javascript

function animateBody() {
    var hash = $(this).val();
    var target_offset = $(hash).offset();
    $('html, body').animate({scrollTop:target_offset.top}, 500);
}

$("#jump_menu select option").click(animateBody);
$("#jump_menu select").change(animateBody);

//Other JQuery/Javascript

Good luck!

Upvotes: 1

Related Questions