sarath sarath - 4 months ago 29
jQuery Question

Switch click and hover events based on width

I want to toggle events based on width. for mobile only click event should work. for desktop hover event should work. while page loading my code working properly when resize my code is not working.
please help me why my code is not working. Thanks in advance

$(document).ready(function(){

function forDesktop(){
$(".popover-controls div").off('click');
$(".popover-controls div").on('hover');
$(".popover-controls div ").hover(function(e){
//popup show code
});

}
function forMobile(){
console.log("mobile");
$(".popover-controls div").off('hover');
$(".popover-controls div").on('click');

$(".popover-controls div").click(function(e){
//popop show

});
}

function process(){
$(window).width() > 600?forDesktop():forMobile();
}
$(window).resize(function(){
process()
});
process();
});

Answer

Its very simple, 1st you cant write this much of code for every event. We have to come up with very simple solution, here is how it works

1st check the width of the Page in JS and assign Desktop/Mobile Class on body :

 function process(){ 
   if( $(window).width() > 600){
     $("body").removeClass("mobile").addClass("desktop");

   }else{
     $("body").removeClass("desktop").addClass("mobile");
   }

}
$(window).resize(function(){
    process()
});

Now, you have execute the command for hover and click:

     $(document).on('mouseover', 'body.mobile .popover-controls div',function(e){
            alert("hover");
        }); 

 $(document).on('click', 'body.desktop .popover-controls div',function(e){
            alert("click");
     console.log("click");
        }); 

I Hope this will work for you. :)

Check the Js fiddle Example: http://jsfiddle.net/asadalikanwal/xcj8p590/ I have just created for you, also i have modified my code