开发者

Triggering same function on both click and keypress

I have the following function which fires when clic开发者_开发百科ked 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);
})  


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.


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!


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);


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜