Animated "show" without jQuery

I want to make a little animation on this last website that I work for. Basically, I need one or two div / show / hide div based on the onClick event on any of the radio buttons or checkboxes (then if the radio / check is A, show div / p if it B then hides it)

The thing is, that is all I would like to use javascript-ify on this particular website, so jQuery looks like a bit of a bust (even a mini version)

Is there a simple [I can’t stress this] way to do this either using vanilla javascript or from some other minimal library [I generally look for something <2kB for events and a little animation (height)]

Any ideas?

Thanks!

Change Thanks to everyone, I just realized that although some of the things I need to do can be done with smart html + js, the rules for displaying / hiding the right divs are so complex that it costs 30 KB, including jQuery (even if it is already cached from CDN), so I will stick with jQuery. Greetings to all :)

edit: JS + CSS3 transition sequence It works :) http://jsfiddle.net/ygZM7/23/

The only thing: if the height has not been previously set (dynamic), the first time you set it, background images (go from a height of 0px).

+8
javascript
source share
8 answers

I came up with my own quick script .. nothing works here:

var AnimationStep = 10; //pixels var AnimationInterval = 100; //milliseconds window.onload = function() { var oDiv = document.getElementById("Div1"); oDiv.style.display = "block"; var height = oDiv.clientHeight; oDiv.style.height = "0px"; Animate(oDiv, height); }; function Animate(element, targetHeight) { var curHeight = element.clientHeight; if (curHeight >= targetHeight) return true; element.style.height = (curHeight + AnimationStep) + "px"; window.setTimeout(function() { Animate(element, targetHeight); }, AnimationInterval); return false; } 

This will “animate” the element with id Div1 , and you can control the speed by playing with two numbers on top: more. A step means that each time an enlarged fragment is displayed, and a shorter interval means faster animation.
This code requires the following style for an element:

 #Div1 { display: none; overflow: hidden; } 

And of course, a live test case: http://jsfiddle.net/yahavbr/BbWCp/

For animating the width, it can also be quite simple (perhaps even at the same time) to achieve a “colder” effect. :)

+6
source share

If you want to make an animation by updating the "height" of the element, thus sorting the effect of "slide down" (or "up"), this should not be too complicated. You just need to make small changes quickly with a timer.

 <div id='animateMe' style='height: 0px; overflow: hidden'> blah blah blah </div> <script> (function() { var div = document.getElementById('animateMe'); var curh = 0, finalh = 100; var interval = setInterval(function() { if (curh === finalh) { clearInterval(interval); return; } curh = curh + 1; div.style.height = curh + 'px'; }, 50); })(); </script> 

This is just a sample; you can hook the code up to an event handler or something else.

+5
source share

You can use CSS transitions. does not work in every browser, but it is acceptable that users in IE7 do not have the same experience as users in Chrome / Safari / FF4.

+1
source share
 <script> function swap(rad) { var p1 = document.getElementById("p1"); var p2 = document.getElementById("p2"); if (rad.value === "1") { p1.style.display = "none"; p2.style.display = "block"; } else { p1.style.display = "block"; p2.style.display = "none"; } return false; } </script> <label><input type="radio" name="r" value="1" onclick="swap(this)" />One</label> <label><input type="radio" name="r" value="2" onclick="swap(this)" />Two</label> <p id="p1">Hi there</p> <p id="p2">Hey there</p> 
+1
source share

For what it's worth, I had the same question, but he wanted to have the height of the element, even if it is not set in style, and even if the element has a display: none. Therefore, my solution is to steal an element, make it invisible, place it somewhere invisible, make it display: block, measure its height with clientHeight, return it to its original location with the original settings, and then perform a sliding one. Here he is:

  function slideElementIn(myid) { mydiv= document.getElementById(myid); if(mydiv.style.display!="none")return; // clientHeight is zero when display is none. So, prepare: inipos = mydiv.style.position; inivisibility = mydiv.style.visibility; iniz = mydiv.style.zIndex; initop = mydiv.style.top; inileft = mydiv.style.left; inioverflow = mydiv.style.overflow; mydiv.style.zIndex = "-999"; mydiv.style.top = "0"; mydiv.style.left = "0"; mydiv.style.visibility = "hidden"; mydiv.style.position = "fixed"; mydiv.style.display = "block"; finHeight = mydiv.clientHeight; // got it! // repair damage: mydiv.style.display = "none"; mydiv.style.position = inipos; mydiv.style.visibility = inivisibility; mydiv.style.zIndex = iniz; mydiv.style.top = initop; mydiv.style.left = inileft; iniHeight = mydiv.style.height; mydiv.style.height = 0; mydiv.style.display = "block"; mydiv.style.overflow="hidden"; var i = 1; // set your counter to 1 function myLoop2 (i,mydiv,finHeight,iniHeight,inioverflow) { // create a loop function setTimeout(function () { // call a 3s setTimeout when the loop is called mydiv.style.height = finHeight * easeIn(i * (1./fadeDuration)); i++; // increment the counter if (i < fadeDuration) { // if the counter < 10, call the loop function myLoop2(i,mydiv,finHeight,iniHeight,inioverflow); // .. again which will trigger another } else { mydiv.style.height = iniHeight; mydiv.style.overflow=inioverflow; } // .. setTimeout() }, 1) } myLoop2(i,mydiv,finHeight,iniHeight,inioverflow); } function slideElementOut(myid) { mydiv= document.getElementById(myid); itsdisplay = mydiv.style.display ; if ( itsdisplay != "none" ) { finHeight = mydiv.clientHeight; iniHeight = mydiv.style.height; inioverflow = mydiv.style.overflow; mydiv.style.overflow = "hidden"; var i = fadeDuration; // set your counter to 1 function myLoop (i,mydiv,finHeight,iniHeight,inioverflow) { // create a loop function setTimeout(function () { // call a 3s setTimeout when the loop is called mydiv.style.height = finHeight * easeOut(i * (1./fadeDuration)); i--; // increment the counter if (i > 0) { // if the counter < 10, call the loop function myLoop(i,mydiv,finHeight,iniHeight,inioverflow); // .. again which will trigger another } else { mydiv.style.display = "none"; mydiv.style.height = iniHeight; mydiv.style.overflow=inioverflow; } // .. setTimeout() }, 1) } myLoop(i,mydiv,finHeight,iniHeight,inioverflow); } } 

I suppose it's worth publishing it here anyway, because when I was looking for my answer, I got to this question, but I only need a few steps. I hope this helps someone.

+1
source share

I recently converted a website to remove its jQuery dependencies, and it used fadeIn() and hide() for an animated tab, such as the user interface, where, if the user clicked on another tab, then the current bookmark instantly disappears. when a new tab quickly disappears.

I would like to avoid creating any kind of animation in Javascript, especially since the CSS3 transition and animation functions are now well supported. Since this question comes from 2011, I suggested that it can do with the update, here is what I used: no jQuery and no manual animations ( setInterval , setTimeout , requestAnimationFrame , etc.):

From this:

 <div id="tabContainer"> <ul> <li class="tab" data-tab="tabPage1">Page 1</li> <li class="tab" data-tab="tabPage2">Page 2</li> <li class="tab" data-tab="tabPage3">Page 3</li> </ul> <div class="tabPage" id="tabPage1"></div> <div class="tabPage" id="tabPage2"></div> <div class="tabPage" id="tabPage3"></div> </div> $('#tabContainer .tab').click(function(e) { // when a tab is clicked: // 1. Hide all other tabs $('#tabContainer .tabPage').hide(); // 2. Show the selected tab, determined from the clicked element `data-tab` attribute: $( '#' + $(this).data('tab') ).fadeIn(); }); 

(and loading 85KB jQuery.min.js ...)

:

 var nodes = document.querySelectorAll('#tabContainer .tab'); for(var i=0; i < nodes.length; i++) { nodes[i].addEventListener('click', function(event) { var tabPages = document.querySelectorAll('#tabContainer .tabPage'); for(var j=0; j < tabPages.length; j++) { tabPages[i].style.display = 'none'; tabPages[i].classList.remove('animFadeIn'); } var tabToShow = document.querySelector('#' + event.currentTarget.dataset['tab']); tabToShow.style.display = ''; tabToShow.classList.add('animFadeIn'); }); } 

And this CSS:

 .animFadeIn { animation: animFadeInAnim 300ms; } @keyframes animFadeInAnim { 0% { display: block; opacity: 0; } 100% { opacity: 1.0; } } 

You cannot use CSS transition because the opacity transition is blocked whenever the display: property changes, but CSS animations support it.

This can be done shorter by replacing the for(var... loops with for(var e of... , however this kind of loop does not yet have broad browser support (as of June 2016).

0
source share

Use the following transition function:

 function transition(style, prop, unit, from, to, duration, callback){ var change = from-to, now = performance.now(), end = now + duration; function anim8(){ now = end - performance.now(); if (now < 0){ style[prop] = to + unit; return callback(); } style[prop] = to + change*now/duration + unit; requestAnimationFrame(anim8); } anim8(); } 

Example:

 transition( document.body.style, 'width', 'vw', // unit (appended onto the end) 95, // start value 50, // end value 5000, // duration (miliseconds) function(){console.log('done!')} // function to run after finished ); function transition(style, prop, unit, from, to, duration, callback) { var change = from - to, now = performance.now(), end = now + duration; function anim8() { now = end - performance.now(); if (now < 0) { style[prop] = to + unit; return callback(); } style[prop] = to + change * now / duration + unit; requestAnimationFrame(anim8); } anim8(); } 
 <body style="border:1px solid">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus at consequat nisl. Vestibulum tempor dapibus venenatis. Donec sed auctor elit. Suspendisse eget lectus nulla. Pellentesque dapibus tempus tortor, eu cursus ligula iaculis ut. Donec a ipsum elit. Suspendisse gravida fringilla dolor, pulvinar scelerisque ante consectetur vitae. 

I sometimes use this convenient feature rather than CSS transions because, to be honest, CSS transitions were not fully thought out. I'm not saying CSS transitions are bad (I use them sometimes), all I say is hard to use them everywhere. It is often quite difficult to synchronize voiding offsetWidth so that the payment only ends in a buggy transition, and then try to compose setTimeout until it becomes unbearably complicated, but still buggy. For what you use transitions for, you may not have this problem, but for what I use them, I have this problem. What they were supposed to include in the specification was the Element.reflow() function, which would go further than just void Element.offsetWidth , and actually try to synchronize and "sort" the transitions. This single function would facilitate my work as dev 10000000000000000000000%.

0
source share

The following animation is fadeIn fadeOut script. You can use it directly. Works like a charm in any browser.

 var TimeToFade = 1000.0; function fade(eid) { var element = document.getElementById(eid); if(element == null) return; if(element.FadeState == null) { if(element.style.opacity == null || element.style.opacity == '' || element.style.opacity == '1') { element.FadeState = 2; } else { element.FadeState = -2; } } if(element.FadeState == 1 || element.FadeState == -1) { element.FadeState = element.FadeState == 1 ? -1 : 1; element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft; } else { element.FadeState = element.FadeState == 2 ? -1 : 1; element.FadeTimeLeft = TimeToFade; setTimeout("animateFade(" + new Date().getTime() + ",'" + eid + "')", 33); } 
-3
source share

All Articles