i trying build animated sidebar slides in , out when click button. quite easy achieve ran in problem when making sidebar 'more' responsive. basically, wanted sidebar 200px wide when width less 500 , 300px wide otherwise. done in media query. problem i've run when resize window sidebar goes out of position if have run function before resizing.
this problem can occur example if user rotates mobile screen whilst using sidebar , feel it's best try , fix it.
here jquery:
function sidebar(){ var menuwidth = $('#menu').width(); if($('#menu-link').hasclass('hidden')){ $('#menu-link').removeclass('hidden'); $('.push').animate({right: "-=" + menuwidth}); }else{ $('#menu-link').addclass('hidden'); $('.push').animate({right: "+=" + menuwidth}); } }; $('body').on('click', '#menu-link', sidebar); the sidebar changes 200px <500 , otherwise 300px. best way code or better keep simple making sidebar 200px though it's not aesthetically pleasing @ larger resolutions.
here link jsfiddle of code https://jsfiddle.net/fqcydqu7/
edit: sorry, explain actual problem - before resize, code runs fine , perfect. however, if run code (ie. open , close sidebar) , resize window media query active see sidebar out of position 100px. opposite happen if reverse order.
okay guys came solution problem.
basically, remove media query css , set div 300px. jquery uses variable updated whenever window resized judge how slide menu. (200px or 300px).
here code:
// variable set 0 default var menuwidth = 0; //call function set variable setwidth(); function setwidth(){ if(windowsize <= 800){ //if less 800px wide, set variable 200px (the menu still 300px) menuwidth = "200px"; }else{ menuwidth = "300px"; //otherwise set variable 300px } } $(window).resize(function(){ //when user resizes window, run setwidth function readjust variable setwidth(); //this re-runs setwidth //the following closes menu if it's open avoid glitches if($('#menu-link').hasclass('hidden')){ $('#menu-link').removeclass('hidden'); $('.push').animate({right: "-=" + menuwidth}); } }); //nav slide function sidebar(){ if($('#menu-link').hasclass('showing')){ //checks see if nav showing or not $('#menu-link').removeclass('showing'); //remove showing tag $('.push').animate({right: "-=" + menuwidth}); //closes nav }else{ //if nav doesnt have showing tag must hidden $('#menu-link').addclass('showing'); //add showing tag $('.push').animate({right: "+=" + menuwidth}); //open nav } }; with code, menu slide out 200px when window less 800px wide , 300px if it's wider. div in correct position if user rotates mobile or changes window width.
Comments
Post a Comment