admin管理员组

文章数量:1425701

I have a boolean variable called isTouchscreen and some on('hover', ...) events. If the isTouchscreen boolean variable equals true then I need to change on('hover') events to on('click') events. Is this possible?

Something like:

 $(".smart-suggestions").on("hover", ".option", function(){
    $('.img-container img').show();
    //and do more stuff....
 });

    if(touchscreen==true){
       //change onhover event to onclick event  
    }

I have a boolean variable called isTouchscreen and some on('hover', ...) events. If the isTouchscreen boolean variable equals true then I need to change on('hover') events to on('click') events. Is this possible?

Something like:

 $(".smart-suggestions").on("hover", ".option", function(){
    $('.img-container img').show();
    //and do more stuff....
 });

    if(touchscreen==true){
       //change onhover event to onclick event  
    }
Share Improve this question edited Dec 24, 2012 at 22:45 user166390 asked Dec 24, 2012 at 22:38 AnchovyLegendAnchovyLegend 12.6k41 gold badges153 silver badges240 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

you could do it this way:

var evt = touchscreen ? 'click' : 'hover';

$(".smart-suggestions").on( evt, ".option", function(){/*.....*/});

Alternate approach if you need both events :

$(".smart-suggestions").on('click hover', ".option", function(event){
       /* create whatever conditions you need*/
      if( event.type=='click' && touchscreen){
            doThis();
       }else{
              doThat();
       }
});

I suggest you always bind the 'on click' event. And conditionally, if touchscreen is false, also bind on hover event.

本文标签: javascriptChanging on(39hover39) to on(39click39) for touchscreen devicesStack Overflow