phantom phantom - 1 month ago 10
Javascript Question

trigger different function dependent on window size resize window

I have created two animations, one for mobile and one for desktop. This works well when the page loads, however when you resize the window the animation doesn't change.

for example if you load the page in desktop size the desktop animation plays when you hover on the appropriate section. However, if I resize the browser to 'mobile size' (less than 1000px) the animation for desktop still plays.

I have approached this countless ways and cannot figure out why it doesn't work as expected.

Please see code below:

var isMobile = isMob();

function isMob() {
if($(window).width() > 1000) {
return false;
}
return true;
}

$(window).resize(function() {
isMobile = isMob();
});

if(isMobile){
mobileAnimate();
}
if(!isMobile){
deskTopAnimate();
}

function deskTopAnimate() {
$('.hover-zone').mouseenter(function(){
desktopAnimateOut.play();
});

$('.desktop-close').click(function(){
desktopAnimateOut.reverse();
})
}

function mobileAnimate() {
$('.hover-zone').click(function(){
animateOut.play();
}
});

$('.mobile-close').click(function(){
animateOut.reverse();
})
}

Answer

These instructions

if(isMobile){
    mobileAnimate(); 
}  
if(!isMobile){  
    deskTopAnimate();
}

are evaluated only at the begining. I think you have to put them into funtion resize, like

$(window).resize(function() {
  isMobile = isMob();
  if(isMobile){
      mobileAnimate(); 
  }  
  if(!isMobile){  
      deskTopAnimate();
  }
}
Comments