AnchovyLegend
AnchovyLegend

Reputation: 12538

Changing on('hover') to on('click') for touchscreen devices?

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  
    }

Upvotes: 3

Views: 1506

Answers (2)

charlietfl
charlietfl

Reputation: 171698

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

Upvotes: 7

hyankov
hyankov

Reputation: 4130

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

Upvotes: 2

Related Questions