Convert Jquery slidetoggle code to Javascript -


how can convert jquery slidetoggle() function javascript?

 var $context = getcontext(context);          $($context).on('click', '.m_menu', function () {             $('.w_nav').slidetoggle();         }); 

well not converting jquery code javascript, rather doing in plain javascript. can achieved in different ways. here 2 comes mind:

html:

<button id="mbtn" onclick="slidetoggle()">slidetoggle</button> <div id="mdiv">some context</div> 

1. using javascript's setinterval :
having boolean value keep track of whether need slideup or slidedown (toggle) , using setinterval increase/decrease height.

jsfiddle demo

javascript:

var open = true; var heightchecked = false; var initheight = 0; var intval = null;  function slidetoggle() {     window.clearinterval(intval);     var mdiv = document.getelementbyid('mdiv');     if(!heightchecked) {         initheight = mdiv.offsetheight;         heightchecked = true;     }     if(open) {         var h = initheight;         open = false;         intval = setinterval(function(){             h--;             mdiv.style.height = h + 'px';             if(h <= 0)                 window.clearinterval(intval);             }, 1         );     }     else {         var h = 0;         open = true;         intval = setinterval(function(){             h++;             mdiv.style.height = h + 'px';             if(h >= initheight)                 window.clearinterval(intval);             }, 1         );     } } 

2. using css3 transition:
getting css3 transition go along javascript make lot easier achieve slide effect. we'll need change height in javascript , rest done.

jsfiddle demo

css:

#mdiv {     /* other styles */     -webkit-transition: 1s ease-in-out;     transition: 1s ease-in-out; } 

javascript:

var open = true; var heightchecked = false; var initheight = 0;  function slidetoggle() {     var mdiv = document.getelementbyid('mdiv');     if(!heightchecked) {         initheight = mdiv.offsetheight;         heightchecked = true;     }     if(open) {         open = false;         mdiv.style.height = '0px';     }     else {         open = true;         mdiv.style.height = initheight + 'px';     } } 

edit:
if want starting height 0, we'll need few changes:

var open = false; //var heightchecked = false; var initheight = 120; //height of element when it's open 

and need comment bit out:

/* if(!heightchecked) {     initheight = mdiv.offsetheight;     heightchecked = true; } */ 

jsfiddle demo


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -