JS DOM Animations & Tricks By albro
hive-169321·@albro·
0.000 HBDJS DOM Animations & Tricks By albro
<center></center> <p> In this post I want to talk about animations in JavaScript. The discussion of animations in JavaScript is very complicated, but in this post you will get to know the main concepts and how DOM animations work in JavaScript. </p> <p> What do you mean by DOM animations, you might ask? I mean, in the web world there are different ways to animate pages, but I want to look at a very simple and basic way to do this, which is done by manipulating the DOM. </p> <h3> Animation through the DOM </h3> <p> The best way to learn animations is by example, so let's first create a simple web page: </p> <pre><code class="language-html"><!DOCTYPE html> <html> <body> <h1>My First JavaScript Animation</h1> <div id="animation">My animation will go here</div> </body> </html></code></pre> <p> Now we need to define the space in which our animation will be done: </p> <pre><code class="language-html"><div id ="container"> <div id ="animate">My animation will go here</div> </div></code></pre> <p> In this code that is going to be added to our main page, I have placed two <code><div></code> elements in a nested form, but we know that <code>div</code>s are only containers for other elements and there's nothing inside them. So let's style these two elements. For the first <code>div</code> (the space where the animation takes place), I put <code>position: relative;</code> and for the second <code>div</code> (which will be the animation itself), I put <code>position: absolute;</code>. Then we add the rest of the styles according to our taste. </p> <pre><code class="language-html"><!Doctype html> <html> <style> #container { width: 400px; height: 400px; position: relative; background: yellow; } #animate { width: 50px; height: 50px; position: absolute; background: red; } </style> <body> <h2>My First JavaScript Animation</h2> <div id="container"> <div id="animate"></div> </div> </body> </html></code></pre> <center></center> <p> If you look at the output, you'll notice that I've turned the first <code>div</code> into a <code>yellow</code> square and placed the second <code>div</code> into a smaller, <code>red</code> square inside. Now I want to make the <code>red</code> square move inside the <code>yellow</code> square, which will be our animation. This is where JavaScript comes in: </p> <pre><code class="language-javascript">function myMove() { var elem = document.getElementById("animate"); var pos = 0; var id = setInterval(frame, 5); function frame() { if (pos == 350) { clearInterval(id); } else { pos++; elem.style.top = pos + 'px'; elem.style.left = pos + 'px'; } } }</code></pre> <p> What do you think this JavaScript code that will be added to our main code later does? </p> <p> As you can see, I have first defined a function and named it <code>myMove</code> (meaning my move). Then I have created a variable called <code>elem</code> (abbreviation of element). From its name, it is clear what I put in this variable: </p> <p> <code>var elem = document.getElementById("animate");</code> </p> <p> If I want to write a statement in JavaScript that takes an element from the DOM, I have to start with <code>document</code> because the main object is in my browser. Then I have used the <code>getElementById</code> statement, which works to get HTML elements based on their <code>id</code>; I have given it <code>animate</code>. </p> <p> Then I have created another variable called <code>pos</code> (abbreviation of position) and I have set its value to <code>zero</code> for now. The third variable is called <code>id</code>, and using the <code>setInterval</code> function, I told it to execute the <code>frame()</code> function every <code>5</code> milliseconds. </p> <p> <i>Why have I used the frame function first and then defined it? How can a function be used before it is defined?</i> </p> <p> In many programming languages, such work is considered an error, but in JavaScript there is a topic called <code>Hoisting</code>. Hoisting makes this code correct. </p> <p> In the <code>frame()</code> function, I have said that <code>if pos == 350</code>, that is, the horizontal and vertical position of the element reaches <code>350</code> pixels, <code>clearInterval</code> to stop moving forward. <i><strong>How do you think I got to </strong></i><code><i><strong>350</strong></i></code><i><strong>?</strong></i> If you remember, the first <code>div</code>, which was the <code>animation</code> space, had a height and width of <code>400</code> pixels, and the second <code>div</code> had a height and width of <code>50</code> pixels. If I want the second <code>div</code> to stay in the first <code>div</code> and not leave it, I have to subtract <code>400</code> from <code>50</code>, which is <code>350</code>! </p> <p> Then I have said that <code>if pos == 350</code>, add one unit to <code>pos</code> (<code>pos++</code>) and after that I have given the following statement: </p> <pre><code class="language-javascript">elem.style.top = pos + 'px'; elem.style.left = pos + 'px';</code></pre> <p> These two statements actually change the element's CSS value. <code>style.top</code> means the code, go to CSS styles, set the distance from the top of this element equal to <code>pos</code> pixel! I have also done this for the distance from the left. On the other hand, I know that the <code>frame()</code> function is executed every <code>5</code> milliseconds by <code>setInterval</code>, which means that one unit is added to <code>pos</code> every <code>5</code> milliseconds, and naturally the distance from the top and left is added by one pixel. This continues until <code>pos</code> equals <code>350</code> pixels and then <code>clearInterval</code> is executed. </p> <p> Now we see the final example: </p> <pre><code class="language-html"><!DOCTYPE html> <html> <style> #container { width: 400px; height: 400px; position: relative; background: yellow; } #animate { width: 50px; height: 50px; position: absolute; background-color: red; } </style> <body> <p><button onclick="myMove()">Click Me</button></p> <div id ="container"> <div id ="animate"></div> </div> <script> function myMove() { var elem = document.getElementById("animate"); var pos = 0; var id = setInterval(frame, 5); function frame() { if (pos == 350) { clearInterval(id); } else { pos++; elem.style.top = pos + "px"; elem.style.left = pos + "px"; } } } </script> </body> </html></code></pre> <h3> Loading animation with JavaScript </h3> <pre><code class="language-html"><!DOCTYPE html> <html> <style> .preloader { height: 100%; width: 100%; background: #fff; position: fixed; left: 0; top: 0; z-index: 10000; perspective: 1600px; perspective-origin: 20% 50%; transition: 0.5s all; opacity: 1; } .spinner { width: 80px; height: 80px; border: 2px solid #f3f3f3; border-top: 3px solid #0088cf; border-radius: 100%; position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; animation: spin 1s infinite linear; } .preloader.fade { opacity: 0; } .b-ico-preloader { background: url(http://weblaboratory.in.ua/wp-content/themes/graphy/images/new_logo.svg); background-size: cover; width: 52px; height: 67px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; animation: ico 5s infinite linear; transform-style: preserve-3d; } @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } @keyframes ico { from { transform: rotateY(0deg); } to { transform: rotateY(360deg); } } </style> <body> <div id ="container"></div> <script> var preload = document.createElement('div'); preload.className = "preloader"; preload.innerHTML = '<div class="b-ico-preloader"></div><div class="spinner"></div>'; document.body.appendChild(preload); </script> </body> </html></code></pre> <h3> Text animation with CSS only </h3> <pre><code class="language-html"><!DOCTYPE html> <html> <style> @import url('https://fonts.googleapis.com/css?family=Roboto:700'); body { margin:0px; font-family:'Roboto'; text-align:center; } #container { color:#999; text-transform: uppercase; font-size:36px; font-weight:bold; padding-top:200px; position:fixed; width:100%; bottom:45%; display:block; } #flip { height:50px; overflow:hidden; } #flip > div > div { color:#fff; padding:4px 12px; height:45px; margin-bottom:45px; display:inline-block; } #flip div:first-child { animation: show 5s linear infinite; } #flip div div { background:#42c58a; } #flip div:first-child div { background:#4ec7f3; } #flip div:last-child div { background:#DC143C; } @keyframes show { 0% {margin-top:-270px;} 5% {margin-top:-180px;} 33% {margin-top:-180px;} 38% {margin-top:-90px;} 66% {margin-top:-90px;} 71% {margin-top:0px;} 99.99% {margin-top:0px;} 100% {margin-top:-270px;} } p { position:fixed; width:100%; bottom:30px; font-size:12px; color:#999; margin-top:200px; } </style> <body> <div id=container> Albro <div id=flip> <div><div>Hive</div></div> <div><div>Blockchain</div></div> <div><div>Blog</div></div> </div> AweSoMe! </div> </body> </html></code></pre> <p> There are many ways to create animations on the web and I hope you enjoyed this post. </p>
👍 pixelfan, hive-129556, peerfinance, dotnetguru, irivers, holovision.stem, lemouth, steemstem-trig, steemstem, howo, aboutcoolscience, robotics101, dna-replication, roelandp, minnowbooster, stemsocial, intrepidphotos, fragmentarion, stem.witness, curie, techslut, dhimmel, samminator, alexander.alexis, tsoldovieri, aidefr, madridbg, sco, emiliomoron, geopolis, temitayo-pelumi, nattybongo, pboulet, lamouthe, metabs, edb, walterjay, abigail-dantes, francostem, gadrian, de-stem, deholt, armandosodano, crowdwitness, noelyss, valth, sustainablyyours, splash-of-angs63, kenadis, alexdory, greddyforce, waivio.curator, zonguin, doctor-cog-diss, enzor, bscrypto, kylealex, therising, brianoflondon, federacion45, neumannsalva, samsemilia7, apshamilton, hamismsf, jpbliberty, podping, sumant, princessmewmew, punchline, marc-allaria, dcrops, thecryptodrive, detlev, fatman, we-are-one, thefoundation, we-are-palcoin, postpromoter, archangel21, fineartnow, achimmertens, justyy, anttn, qberry, quinnertronics, meritocracy, kaylinart, rhemagames, bitrocker2020, felt.buzz, photohunt, bflanagin, oks2crypto, revo, maverickfoo, gunthertopp, baltai, sunsea, sbtofficial, cloh76, rocky1, bartosz546, modernzorker, yadamaniart, empath, steveconnor, steemean, tfeldman, steemcryptosicko, boxcarblue, dandesign86, arunava, aries90, enjar, cheese4ead, hetty-rowan, meno, irgendwo, jjerryhan, mobbs, minerthreat, stayoutoftherz, thelittlebank, humbe, yixn, dynamicrypto, laxam, be-alysha, itharagaian, rt395, deadzy, letenebreux, cercle, bastionpm, hive-143869, entraide.rewards, cookaiss, independance, isiksenpalvoja, nabab, ledonjon, jayna, metroair, buildahouse, emeraldtiger, minava.museum, lordnight72, hive-fr, sapphireleopard, rmach, mcsvi, ibt-survival, forykw, sanderjansenart, celinavisaez, mafufuma, reggaesteem, holovision.cash, atheistrepublic, jerrybanfield, cryptictruth, juecoree, stem-espanol, duke77, iamphysical, sandracarrascal, miguelangel2801, tomastonyperez, elvigia, josedelacruz, erickyoussif, andrick, fran.frey, giulyfarci52, ydavgonzalez, uche-nna, hk-curation, lorenzor, azulear, hashkings, pepeymeli, xclanleo, liuke96player, infernalcoliseum, rondonshneezy, fefe99, psicoluigi, sweetval, nfttunz, eric-boucher, robertbira, gribouille, dranren, eternalsuccess, cyprianj, ennyta, endopediatria, dandays, riyaverma123, bluefinstudios, gamersclassified, agileautomation, yggdrasil.laguna, stemgeeks, babytarazkp, abh12345.stem, slider2990, dorkpower, juecoree.stem, saboin.stem, sillybilly, meestemboom,