<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Reitwiec Shandilya on Medium]]></title>
        <description><![CDATA[Stories by Reitwiec Shandilya on Medium]]></description>
        <link>https://medium.com/@reitwiec_97577?source=rss-53b026960d34------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*OhFscOA_4L3VyisK.jpg</url>
            <title>Stories by Reitwiec Shandilya on Medium</title>
            <link>https://medium.com/@reitwiec_97577?source=rss-53b026960d34------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 03:54:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@reitwiec_97577/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Day 12— Mutations in DOM]]></title>
            <link>https://medium.com/iecse-hashtag/day-12-mutations-in-dom-1ca337afb4d4?source=rss-53b026960d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ca337afb4d4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[user-interface]]></category>
            <dc:creator><![CDATA[Reitwiec Shandilya]]></dc:creator>
            <pubDate>Wed, 25 Dec 2019 04:32:14 GMT</pubDate>
            <atom:updated>2019-12-25T04:32:14.658Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tracking DOM changes with Mutation Observer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WLrSy5GsTphTK4fSdo_0sA.png" /></figure><h3>The 12 Days of JS?</h3><blockquote><strong>12 Days of JS</strong> is a series where we will tackle a new problem <em>every day</em> leading to Christmas, and solve it with the help of JavaScript ❤️. <strong>This isn’t a JavaScript 101 course</strong> but a way to improve the application of JavaScript in your projects! We aim to learn by application — encountering many new situations while talking about the hows, the whys and the whats we use to solve them.</blockquote><h4>As we come to the end of this series, I thought we could make something people haven’t been exposed to yet, tracking changes/mutations in your DOM.</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F26hisnlvJAkXAVDhK%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26hisnlvJAkXAVDhK%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F26hisnlvJAkXAVDhK%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/d372ce7f7224e4ea51e40313b0935d28/href">https://medium.com/media/d372ce7f7224e4ea51e40313b0935d28/href</a></iframe><p><em>Before we start I just want to point out that I’m using some ES6 features like </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const"><em>const</em></a><em> and </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let"><em>let</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions"><em>arrow functions</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla"><em>etc.</em></a><em> If you are not familiar with those, check the links provided to learn more.</em></p><h3>Basic project</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fowl0y&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fowl0y&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fowl0y%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/8414c610ae8531cf5bd3d8dda3a23da8/href">https://medium.com/media/8414c610ae8531cf5bd3d8dda3a23da8/href</a></iframe><p>Inside the HTML we just have a &lt;h1&gt; tag followed by a &lt;p&gt; tag. Nothing fancy going over here.</p><p>Now my <strong>mutation observer</strong>, is something that we are going to use to track, when changes take place. So inside our script I’ve declared a <strong>global variable </strong>called observer , and I will use this to hold my mutation observer. And then, when the HTML finishes loading I am calling the init() function with the help of an <strong>event listener</strong> of event type DOMContentLoaded.</p><p>Inside the init() function, I am getting the <strong>reference</strong> to the &lt;p&gt; tag and storing it in a variable p. I am then adding an <strong>event listener</strong> of event type click to the &lt;p&gt; tag. So if I click on the paragraph, I want to call a function changeMe() and I want to make some changes in that HTML.</p><h3>Setting up Observer</h3><p>Now, I want to track when those changes take place, and the way we do it is with the help of the following two lines</p><pre><strong><em>observer</em></strong> = <em>new</em> <strong>MutationObserver</strong>(<strong>mutated</strong>);</pre><pre>observer.<strong>observe</strong>(<strong>p</strong>, <strong>config</strong>);</pre><p>We create a <em>new</em> <a href="https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver">MutationObserver</a> and pass in the <strong>function</strong> that we want to call, here mutated() is our callback function, every time the changes take place. And then, we call the observe() method, saying which element we want to observe. So since we want to observe p we have passed it in along with a set of rules or conditions under which I am going to observe it, that is the config object here.</p><p>Let’s have a look at what all we can have inside our config object:</p><ul><li>attributes : Do you want to track changes in the <strong>existing attributes</strong>? Like we have a title attribute associated with our &lt;p&gt; tag.</li><li>attributeOldValue : Do you want to be able to access the <strong>old attributes</strong> along with the new ones?</li><li>attributeFilter : Any <strong>specific</strong> attributes you want to watch?</li><li>childList : Track changes in anything <strong>inside of the element</strong> that we are <strong>observing</strong>. Like it’s text nodes, child nodes etc.</li><li>subTree : It’s similar to childList , but childList only allows us to go 1 level deep, if you want to go deeper, we’ll make use of subTree.</li><li>characterData and characterOldValue : To track the changes to a specific text node.</li></ul><p>So, we can define our config object like below</p><pre>let <strong><em>config</em></strong> = {</pre><pre><strong>    attributes</strong>: <strong>true</strong>,</pre><pre><strong>    attributeOldValue</strong>: <strong>true</strong>,</pre><pre><strong>    attributeFilter</strong>: [&quot;<strong>data-thing</strong>&quot;, &quot;<strong>title</strong>&quot;, &quot;<strong>style</strong>&quot;],</pre><pre><strong>    childList</strong>: <strong>true</strong>,</pre><pre><strong>    subTree</strong>: <strong>true</strong>,</pre><pre><strong>    characterData</strong>: <strong>false</strong>,<br><strong>    <br>    characterDataOldValue</strong>: <strong>false</strong></pre><pre>};</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fplzd9&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fplzd9&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fplzd9%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/31406d324b1d7d271cb051ff0ce6300a/href">https://medium.com/media/31406d324b1d7d271cb051ff0ce6300a/href</a></iframe><p>One of either attribute , childList or characterData have to be there inside the config object.</p><h3>Mutated callback function</h3><p>So, the mutated() method receives an argument, let’s call it mutationList. It is basically a list of changes that have just taken place.</p><p>mutationList is just an array with all the mutations, so I can just loop through the entire list and check what kind of mutation it is. Each element of the mutationList is called a <strong>Mutation Record.</strong> Each record provides us with certain properties that we can make use of.</p><pre>//target - Element</pre><pre>//addNodes - NodeList</pre><pre>//removedNodes - NodeList</pre><pre>//oldValue </pre><pre>//attributeName</pre><pre>//attributeNamespace</pre><pre>//nextSibling - Element / textNode</pre><pre>//previousSibling - Element / textNode</pre><pre>//type &#39;attributes&#39; or &#39;childList&#39;</pre><p>To stop observing the element, we use <strong>observer.disconnect()</strong>.</p><p>Let’s try changing the text content of p whenever we click on it!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F92ie8&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F92ie8&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F92ie8%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/52e42fe95eaef36569d2faee266bddc7/href">https://medium.com/media/52e42fe95eaef36569d2faee266bddc7/href</a></iframe><p>If we check out our console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*wF2JJDqs8KHdJiQtz_jO_Q.png" /></figure><p>The null value that you are seeing in front of certain properties mean that there wasn’t any mutation in that property.</p><p>If we check out the addedNodes and the removedNodes property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*jROh0M5gjSc3Qpzts59OFg.png" /></figure><p>Both of them are NodeLists. removedNode has two nodes: comment which is the character data, text which is the main content. Similarly addedNodes has only one node: text which is the new replaced content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*be-98MV9tF62Fw1dxaOwGw.png" /></figure><p>Let’s play a little more with it and make a few more changes.</p><pre>let <strong><em>span</em></strong> = document.<strong>createElement</strong>(&quot;<strong>span</strong>&quot;);</pre><pre>span.<strong>textContent</strong> = &quot; <strong>I am new here</strong>&quot;;</pre><pre>p.appendChild(<strong>span</strong>);</pre><pre>p.<strong>title</strong> = &quot;<strong>New Title</strong>&quot;;  <em>//here we can make use of the oldValue property</em></pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fb44k7&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fb44k7&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fb44k7%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/81c697a7ff57e09a65f755e3e170ad5f/href">https://medium.com/media/81c697a7ff57e09a65f755e3e170ad5f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Id-VVfCelDZ-W4C49xmIg.png" /><figcaption>Here, old value of the title was <strong>mouseover text</strong></figcaption></figure><p>So in this way we can keep track of any mutations that occur in our DOM.</p><h3>Where do we make use of this?</h3><ul><li>Initialising when an element becomes available on the page. Usually we use something like DOMContentLoaded to initialise code which depends on elements on the page. Those events don’t fire until the entire DOM has loaded. Mutation Observer allows us to detect when any element becomes available, allowing us to initialise code which depends on that element at the exact first moment it’s possible.</li><li>Making text editors. Something like a markdown editor, where you enter the text as markdown, and then the editor converts it to HTML for it to be displayed on a website.</li><li>Lazy-loading of images or other content as a page is scrolled.</li><li>Deciding whether or not to perform tasks or animation processes based on whether or not the user will see the result.</li><li>Implementing “infinite scrolling” web sites, where more and more content is loaded and rendered as you scroll, so that the user doesn’t have to flip through pages.</li></ul><p>And a lot more!</p><h4>Congratulation 🎉 ! You have just completed the last JavaScript challenge and have successfully completed the entire series.</h4><p>All of the above-written code is available on <a href="https://github.com/reitwiec/12DaysOfJS"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ca337afb4d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/day-12-mutations-in-dom-1ca337afb4d4">Day 12— Mutations in DOM</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 11 — State Machines for User Interaction in JavaScript]]></title>
            <link>https://medium.com/iecse-hashtag/day-11-state-machines-for-user-interaction-in-javascript-af831771bc6b?source=rss-53b026960d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/af831771bc6b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[user-interface]]></category>
            <category><![CDATA[user-interaction]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[state-machine]]></category>
            <dc:creator><![CDATA[Reitwiec Shandilya]]></dc:creator>
            <pubDate>Tue, 24 Dec 2019 05:27:18 GMT</pubDate>
            <atom:updated>2019-12-24T05:27:18.279Z</atom:updated>
            <content:encoded><![CDATA[<h3>Day 11 — State Machines for User Interaction in JavaScript</h3><h4>Finite State Machines implementation for improving User Interaction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2CB9wnDUZFRQ6DJ9BSnwQ.png" /></figure><h3>The 12 Days of JS?</h3><blockquote><strong>12 Days of JS</strong> is a series where we will tackle a new problem <em>every day</em> leading to Christmas, and solve it with the help of JavaScript ❤️. <strong>This isn’t a JavaScript 101 course</strong> but a way to improve the application of JavaScript in your projects! We aim to learn by application — encountering many new situations while talking about the hows, the whys and the whats we use to solve them.</blockquote><h4>As we come close to the end of this series, I thought we could end this series on a big note. There are a lot of people who are unaware of the concept of Finite State Machines and their usefulness in User Interaction.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/0*ltCFABATj2L-Zu-M.png" /></figure><p><em>Before we start I just want to point out that I’m using some ES6 features like </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const"><em>const</em></a><em> and </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let"><em>let</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions"><em>arrow functions</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla"><em>etc.</em></a><em> If you are not familiar with those, check the links provided to learn more.</em></p><h3>What is a State Machine?</h3><p>A state machine is a tool to manage <strong>state</strong> in your app. <strong>So then, what is a state?</strong> State is the current situation your app is in.</p><p>You might have used variables like isLoading, isLoggedIn, or maybe something like currentUser, so these are all variables that implicitly define our state. <strong>What do I mean by implicit?</strong></p><p>For example, if our component or app is in a loading state we may put this flag isLoading = true , and that is implicitly saying that this is loading and we can assume that it is loading. If we were to do something like &quot;The State is Loading&quot; , that would be explicitly defining our state.</p><p>So what state machines do is that it <strong>explicitly/clearly</strong> defines the state of the app.</p><h4>What is the meaning of finite here?</h4><p>It means, there exists <strong>finite number</strong> of states in our machine.</p><p>FSMs can be represented by a <strong>graph</strong>. The graph helps us understand that I can be only in one state at a time, and there are rules for transitioning from one state to another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*ymHVOwFrm3K4L-QI.png" /><figcaption>A simple FSM for a login form</figcaption></figure><p>If we have a FSM defined like above, then we can share this with our co-workers, designers for better understanding of the functioning of the application.</p><h4>The above FSM can be represented by a JavaScript object like this.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a9e1ce265a36ba45f91934054f46f9d/href">https://medium.com/media/2a9e1ce265a36ba45f91934054f46f9d/href</a></iframe><p>Let’s try and understand what’s going on over here.</p><p>There is always only <strong>one</strong> entry-point/initial state into a FSM. Here, we have defined <strong>idle</strong> state as our <strong>initial</strong> state. We then have a key states which is one big object consisting all the states. Inside this object, all the states are defined as keys. Inside each state there is a key on , which basically says, on this <strong>event</strong>, change the state to the specified state.</p><p>Like, if I’m on loading state and I hear an event called RESOLVE, I will go to the state success.</p><p>Now, because of the defined paths, it gives you clear guidelines to help you debug and figure out how you’re working. For example, if I’m on the loading state and my isLoading variable is false , I know there is something wrong with it and I also know that there are only a finite paths to reach the loading state, so I can just trace down the paths and figure out a way to solve the bug.</p><h3>FSM Paradigm</h3><p>The above example is of a login form, now if I click on the submit button twice, what will happen? Is it supposed to submit twice? So, these are things you usually have to manually handle. But if you’re using a state machine, you’re using a paradigm:</p><h4>Event → State → Action</h4><p>What most people use is: <strong>Event → Action</strong> paradigm, where you are constantly listening to events and all those events will take an action. For example, you listen for a click event on a button and as soon as you hear one, you dispatch an action.</p><p>So what the difference is. you’ll get that same <strong>event</strong> <em>click</em>, and then you’ll transfer the state. Let’s say your event is submit, so you transfer state to loading and then the loading state is responsible for dispatching the action, and at our loading state we don’t have an event of submit, so we don’t have to worry about clicking the button twice. Thus, defining a very clear pathway for our app to follow.</p><h3>XSTATE library</h3><p>Most people use the<strong> </strong><a href="https://github.com/davidkpiano/xstate"><strong>XSTATE</strong></a> library for implementing the the state machine. So, what you do is define your state in a JavaScript object, and then you pass it to XSTATE. After this, it provides us with certain methods that you can make use of on the state. Methods like the transition method that allows you to transition from one state to another.</p><h3>Let’s make a simple application to wet our feet</h3><p>I came up with this simple state chart that I want use to build my application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wl6zgbBCigVu87rYjEw3KQ.png" /></figure><p>Here, we have <strong>nested</strong> states involved. At the first level, we have <strong>two</strong> states, on and off. The initial state is off state, if there is an event CLICK I want to transition into the on state, inside which we have <strong>another machine</strong>. So in this second level, we have <strong>three</strong> states, red, yellow and green. Now, whenever there is an event STEP, I want to transition into the next state. Remember, our on state also has an event EVENT attached to it, so whenever it hears EVENT it’ll go back to the off state.</p><p>Too much going on? Let’s try to write it as a Javascript Object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f581b9afe3387b51f5834bc5485d5003/href">https://medium.com/media/f581b9afe3387b51f5834bc5485d5003/href</a></iframe><h3>Basic Setup</h3><p>Here is the breakdown of the required HTML and CSS.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fhq6r1&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fhq6r1&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fhq6r1%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/040a85de76167dc53f92c0e4fe1b7d93/href">https://medium.com/media/040a85de76167dc53f92c0e4fe1b7d93/href</a></iframe><p>With the help of <a href="https://www.npmjs.com/"><strong>npm</strong></a>, let’s install <strong>xstate</strong>.</p><pre>npm install xstate</pre><p>Inside out <strong>script.js</strong> file, lets import Machine and matchesState from xstate .</p><pre>import { <strong>Machine, matchesState</strong> } from &#39;<strong>xstate</strong>&#39;</pre><p>Machine will allow us to create our state machine by passing on the JavaScript object describing the state.</p><p>matchesState will allow us to check and match if we’re on the right state.</p><pre>import { <strong>interpret</strong> } from &#39;<strong>xstate/lib/interpreter</strong>&#39;</pre><p>Our interpreter will take a machine as an argument, and expose a set of methods that can be used to get the current state of the machine or attempt a transition on the machine.</p><h3>Building the machine</h3><p>Let’s now generate our machine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f925e9c9fdef2dfaf22c126e9b39137f/href">https://medium.com/media/f925e9c9fdef2dfaf22c126e9b39137f/href</a></iframe><p>To manipulate our DOM elements, let’s get the references to all the required elements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e220b742113dc41c85b1f83ca28d9ca7/href">https://medium.com/media/e220b742113dc41c85b1f83ca28d9ca7/href</a></iframe><p>With the help of the interpret that we have imported, let’s create an interpreter instance of our onOffMachine FSM.</p><pre>const <strong><em>onOffInterpreter</em></strong> = <strong>interpret</strong>(<strong>onOffMachine</strong>)</pre><p>We can now interact and send events to our machine with the help of the onOffInterpreter .</p><p>Now when we created onOffInterpreter , we exposed a set of methods that’ll allow us do <strong>something</strong> whenever there is a <strong>transition</strong> in state.</p><p>The onTransition() method takes an argument, which is another function that is executed every time the transition occurs. The onTransition() method also passes an argument to that function, and that argument is the reference to our current state.</p><p>I will call that function render(). So, whenever a state transition occurs, the render() function is called.</p><pre>onOffInterpreter.<strong>onTransition</strong>(<strong>render</strong>)</pre><p>I will define the render() function later on.</p><p>Let’s not go ahead and initialise our interpreter with the help of the .init() method.</p><pre>onOffInterpreter.init()</pre><h3>How do we send events to machine?</h3><p>Earlier, we had stored the references to certain DOM elements in a few variables. One of the references was to the onOffBtn, that’ll turn our traffic light <strong>ON</strong> and <strong>OFF</strong>.</p><p>We can now just access the <a href="https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick_dom">onclick</a> property of the onOffBtn like this</p><pre><strong>onOffBtn</strong>.<strong>onclick</strong> = () =&gt; {</pre><pre>    <strong>onOffInterpreter</strong>.<strong>send</strong>(&#39;<strong>CLICK</strong>&#39;)</pre><pre>}</pre><p>.send() method provided by <strong>xstate</strong>, allows us to send events to the machine. So whenever the user clicks on the onOffBtn, we want to send a CLICK event to the machine.</p><p>Similarly we want to change the colours of the traffic light in steps with the help of a button. We have stored the reference of that button in stepBtn.</p><pre><strong>stepBtn.onclick</strong> = () =&gt; {</pre><pre>    <strong>onOffInterpreter.send</strong>(&#39;<strong>STEP</strong>&#39;)</pre><pre>}</pre><p>So whenever the step button is clicked, a STEP event occurs and is sent to the machine.</p><h3>The render function</h3><p>The remaining code is fairly easier and straightforward.</p><pre>function render (state) {</pre><pre>........ do something here</pre><pre>}</pre><p>So at this point, we have a <strong>function</strong> called <strong>render</strong>, and have the current state stored in the argument state.</p><p>If I go ahead and console.log(state), let’s see what we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mLtIVWDQGGbuPZRr2vqWfw.png" /></figure><p>There is a lot going on here. But for now, let’s concentrate on the value property. If you notice, value : &quot;off&quot; , that’s basically the current value of out state. Since we had initialised it with off state, it’s currently on off state.</p><p>This means, I can go and grab that value from the state variable and store in some other variable. I’m going to call that variable stateValue .</p><pre>const <strong><em>stateValue</em></strong> = state.<strong>value</strong></pre><p>If you remember, we had imported something called <a href="https://xstate.js.org/api/globals.html#matchesstate">matchesState</a>. We can use that method to go and compare the states as per our requirement. It takes in two arguments that we need to compare, returns a <strong>boolean value</strong>.</p><p>I will check my traffic light is on or off.</p><pre>const <strong><em>isOn</em></strong> = <strong>matchesState</strong>(&#39;<strong>on</strong>&#39;, <strong>stateValue</strong>)</pre><p>Now, since know the status of the state and which state we are on, I’m simply just going to go ahead and add a little CSS.</p><pre>onOffBtn.<strong>innerText</strong> = isOn ? &#39;<strong>On</strong>&#39; : &#39;<strong>Off</strong>&#39;</pre><pre>onOffBtn.style.<strong>backgroundColor</strong> = <strong>isOn</strong> ? &#39;<strong>green</strong>&#39; : &#39;<strong>red</strong>&#39;</pre><pre>lightsContainer.style.<strong>display</strong> = <strong>isOn</strong> ? &#39;<strong>flex</strong>&#39; : &#39;<strong>none</strong>&#39;</pre><p>Now all is cool if my state if on off state. But what happens when it turns <strong>on</strong>? Let me console log the value of state again, but this time when it’s on .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*JoK-_e2Vol7psQ00nmnR2A.gif" /></figure><p>Interesting… So we get an object. But what does it mean? Remember how we had set the initial state of the traffic light to be red?</p><p>So this object basically means that, we are on the on state, and inside that we are on the red state.</p><p>With the help of <a href="https://xstate.js.org/api/globals.html#matchesstate">matchesState</a> , I will again try to turn the red, yellow and green lights on.</p><pre>redLight.<strong>classList</strong>.<strong>toggle</strong>(&#39;<strong>active</strong>&#39;, <strong>matchesState</strong>(&#39;<strong>on.red</strong>&#39;, <strong>stateValue</strong>))</pre><pre>yellowLight.<strong>classList</strong>.<strong>toggle</strong>(&#39;<strong>active</strong>&#39;, <strong>matchesState</strong>(&#39;<strong>on.yellow</strong>&#39;, <strong>stateValue</strong>))</pre><pre>greenLight.<strong>classList</strong>.<strong>toggle</strong>(&#39;<strong>active</strong>&#39;, <strong>matchesState</strong>(&#39;<strong>on.green</strong>&#39;, <strong>stateValue</strong>))</pre><p>Let’s check if our machine is working properly or not!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fjyvci&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fjyvci&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fjyvci%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/8924edc20aad5abbb2e5f94d5f9adbd7/href">https://medium.com/media/8924edc20aad5abbb2e5f94d5f9adbd7/href</a></iframe><blockquote>So this was an introduction to Finite State Machines in JavaScript. There is a lot more to explore here. Your next step in this learning process could be to learn how to start services, like how to make async requests in FSM and then based on the response we decide to go in some state. You can even go ahead and run multiple machines in parallel. A good example would be a text editor, how we can have a <strong>bold</strong> state <em>and an </em><a href="#"><em>underlined</em></a><em> state individually, we can even have them both </em><a href="#"><strong>together</strong></a><strong>.</strong></blockquote><h4>Congratulation 🎉 ! You have just completed the eleventh JavaScript challenge and I hope you have some basic understanding of State Machines now.</h4><p>All of the above-written code is available on <a href="https://github.com/reitwiec/12DaysOfJS"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af831771bc6b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/day-11-state-machines-for-user-interaction-in-javascript-af831771bc6b">Day 11 — State Machines for User Interaction in JavaScript</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 10— Implementing Typeahead Search]]></title>
            <link>https://medium.com/iecse-hashtag/day-10-implementing-typeahead-search-f994298e05d1?source=rss-53b026960d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/f994298e05d1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[regex]]></category>
            <dc:creator><![CDATA[Reitwiec Shandilya]]></dc:creator>
            <pubDate>Mon, 23 Dec 2019 06:20:36 GMT</pubDate>
            <atom:updated>2019-12-23T06:20:36.346Z</atom:updated>
            <content:encoded><![CDATA[<h4>Today we build an Ajax type ahead</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mbPZuhf3kO67IVOPtWe3hQ.png" /></figure><h3>The 12 Days of JS?</h3><blockquote><strong><em>12 Days of JS</em></strong><em> is a series where we will tackle a new problem every day leading to Christmas, and solve it with the help of JavaScript ❤️. </em><strong><em>This isn’t a JavaScript 101 course</em></strong><em> but a way to improve the application of JavaScript in your projects! We aim to learn by application — encountering many new situations while talking about the hows, the whys and the whats we use to solve them.</em></blockquote><h4>Today we will make use of many concepts like fetch API, JSON parsing, Regex, working with DOM elements etc.</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FwONkjqOHlEl62zgqzG%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FwONkjqOHlEl62zgqzG%2Fsource.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FwONkjqOHlEl62zgqzG%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d187025497d6928123d76b48ffde585/href">https://medium.com/media/6d187025497d6928123d76b48ffde585/href</a></iframe><p><em>Before we start I just want to point out that I’m using some ES6 features like </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const"><em>const</em></a><em> and </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let"><em>let</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions"><em>arrow functions</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla"><em>etc.</em></a><em> If you are not familiar with those, check the provided links to learn more.</em></p><h3>What is typeahead search?</h3><p>In simple terms, it’s a way of filtering out items by checking if the user’s input is a <strong>substring</strong> of the item, if it is, then we will display it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*jXElvEVIMpDrW6TXM1VSHA.png" /><figcaption>Here is an example</figcaption></figure><p>For today’s challenge we’ll be getting our data from this endpoint</p><pre>const <strong><em>endpoint</em></strong> =</pre><pre>&quot;<a href="https://gist.githubusercontent.com/reitwiec/708b4ec1b036aea2a8bac2b983223121/raw/433520cd58f1446c08631c59cef0a0f4bdcf15ca/states.json"><strong>https://gist.githubusercontent.com/reitwiec/708b4ec1b036aea2a8bac2b983223121/raw/433520cd58f1446c08631c59cef0a0f4bdcf15ca/states.json</strong></a>&quot;;</pre><h3>Fetching</h3><p>So the first thing that we have to do is go ahead and fetch the data, and once that data is back, we’ll filter that data out.</p><p>Lets first go ahead and declare a variable to store all the <a href="https://en.wikipedia.org/wiki/States_and_union_territories_of_India"><strong>states</strong></a> in. If you check out the endpoint, you’ll realise it returns an array of objects. So let’s declare a variable states which will be an <strong>array</strong>.</p><pre>const <strong><em>states</em></strong> = []</pre><p>To fetch the data, we’ll use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch"><strong><em>fetch()</em></strong></a> method that the browser provides. This fetch method returns something called <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch"><em>promise</em></a>. In simple terms a promise is something that will eventually happen.</p><pre>const <strong><em>prom</em></strong> = fetch(<strong>endpoint</strong>);</pre><pre>console.log(<strong>prom</strong>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*pLMM9JCt-rUhk9z2woE2ZA.png" /></figure><p>Now, the way we can work with this promise is, by using the .then() method against it and it’s going to return to us a blob of data.</p><pre>fetch(<strong>endpoint</strong>).then(<strong>blob</strong> =&gt; console.log(<strong>blob</strong>));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_yDflu1r8t45KnRE-7bDQ.png" /></figure><h4>What’s happening here? Where is our data?</h4><p>The data that is coming from fetch, it doesn’t know what kind of data it is. <strong>Is it an image</strong>? <strong>Is it some HTML</strong>? We, explicitly know that it is <a href="https://www.json.org/json-en.html"><strong>JSON</strong></a>.</p><p>Okay, so <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse">JSON.parse()</a> should work right? But no, it doesn’t. If first need to convert the information into JSON.</p><p>If we checkout the prototype of the the <strong>blob</strong>, you will notice that it has a method called <a href="https://developer.mozilla.org/en-US/docs/Web/API/Body/json">.json()</a>. We can use this to convert the received data into JSON. Now that will also return a promise, and that will give you the raw data.</p><pre>fetch(<strong><em>endpoint</em></strong>)</pre><pre>.<strong>then</strong>(<strong>blob</strong> =&gt; <strong>blob</strong>.<strong>json</strong>())</pre><pre>.<strong>then</strong>(<strong>data</strong> =&gt; console.log(<strong>data</strong>));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxVNzSe6mFjZKR1mzwFzJg.png" /></figure><p>We get an array will all the objects.</p><p>I will now go ahead and store that data in our states variable. Now, our variable is defined as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const"><strong>const</strong></a>, so we can’t so go and assign the variable like <strong>states = data</strong>. What we could do is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push"><strong>push</strong></a> the data, after <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax"><strong>spreading</strong></a> the data array.</p><pre>const <strong>states</strong> = [];</pre><pre>fetch(<strong>endpoint</strong>)</pre><pre>.then(<strong>blob</strong> =&gt; <strong>blob</strong>.json())</pre><pre>.then(<strong>data</strong> =&gt; states.<strong>push</strong>(<strong>...data</strong>));</pre><p>Now that we have fetched the data and stored it, we can make the basic setup with some <strong>HTML</strong> and <strong>CSS</strong>.</p><h3>Basic Setup</h3><p>Here is a breakdown of the initial setup</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FabzWWLg%3Fheight%3D600%26slug-hash%3DabzWWLg%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FabzWWLg&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/36006a3644744d124301b9034ea01823/href">https://medium.com/media/36006a3644744d124301b9034ea01823/href</a></iframe><p>It’s just a simple form with an input for searching the states, with some good amount of CSS.</p><p>Now, let’s start implementing the typeahead search!</p><h3>Find me</h3><p>When someone then types in the input, I want to run a function that will take the states array and <strong>filter down into a subset</strong> which you can use.</p><p>I will call that function findMatches(wordToMatch, states). Inside this function I will use the filter() function to filter based on some criteria.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bd28ea487eaaaf20fafb80b171e225d/href">https://medium.com/media/4bd28ea487eaaaf20fafb80b171e225d/href</a></iframe><p>Let’s say if I had to check if the string &quot;del&quot; matched to some word in a variable state, I would use a <a href="https://www.regular-expressions.info/"><strong>regular expression</strong></a> to do so.</p><pre>state.<strong><em>match</em></strong>(/<strong>del</strong>/i) </pre><pre><em>//this returns a boolean value</em></pre><h4>But, in this case the string is stored in a <strong>variable</strong>, so how do we use it?</h4><p>The way we do it is by creating our <strong>own</strong> regular expression with the help of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp">RegEx()</a> constructor.</p><pre>const <strong><em>regex</em></strong> = new <strong>RegExp</strong>(<strong>wordToMatch</strong>, &#39;<strong>gi</strong>&#39;)</pre><p>Here</p><ul><li>g is global- meaning it will look through the entire string.</li><li>i is insensitive- meaning it is not case sensitive.</li></ul><p>Now, we can use this regex inside the match() function to check if it is satisfied.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5460ef4cedb61c995906c4d8a972d5ba/href">https://medium.com/media/5460ef4cedb61c995906c4d8a972d5ba/href</a></iframe><p>Let’s check if this function is working!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iHi9CVTpaP0f9wCSMrPFvg.png" /><figcaption>Testing in the console</figcaption></figure><h4>It returns an array with all the states that match.</h4><p>Now we can go ahead a make a function that’ll display all the matched values!</p><h3>Grabbing the input</h3><p>I will name that method displayMatches() and for now let it be like this.</p><pre>function <strong>displayMatches</strong>(){</pre><pre>console.log(this.<strong>value)</strong>;   //the value that will come from the input</pre><pre>}</pre><p>Let’s grab our <strong>search input</strong> and even the ul which we will use to display the matched states. We will use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector">querySelector()</a> method for doing so.</p><pre>const <strong><em>searchInput</em></strong> = document.<strong>querySelector</strong>(&#39;<strong>.search</strong>&#39;);</pre><pre>const <strong><em>suggestions</em></strong> = document.<strong>querySelector</strong>(&#39;<strong>.suggestions</strong>&#39;);</pre><p>Now we can go ahead and add an <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventListener"><strong>event listener</strong></a> of event type <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event"><strong>input</strong></a> to the searchInput reference, and whenever the input changes, we will call the displayMatches() method.</p><pre>searchInput.<strong><em>addEventListener</em></strong>(&#39;<strong>input</strong>&#39;, <strong>displayMatches</strong>);</pre><p>I will now called the findMatches() method inside displayMatches() and store the returned array in a variable called matchedArray.</p><pre>function <strong>displayMatches</strong>() {</pre><pre>const <strong>matchedArray</strong> = <strong>findMatches</strong>(this.<strong>value</strong>, <strong>states</strong>);</pre><pre>console.log(<strong>matchedArray</strong>);</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDNexaNOv_MQ4wofpKQrlQ.png" /></figure><h4>Great! So now we have the required data.</h4><h3>Inserting the new HTML</h3><p>I will now just loop through the matchedArray with the help of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map"><strong>map</strong></a> function, and return some required HTML.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56a79d43af94835096a3f3990f4d11b4/href">https://medium.com/media/56a79d43af94835096a3f3990f4d11b4/href</a></iframe><p>Once we have the required HTML in html , we can just change the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML"><strong>innerHTML</strong></a> of suggestions.</p><h3>And we are done!</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FXWJRgrW%3Fheight%3D600%26slug-hash%3DXWJRgrW%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FXWJRgrW&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a0b84361dd19ca9bcc799b25383c52d/href">https://medium.com/media/1a0b84361dd19ca9bcc799b25383c52d/href</a></iframe><h3>Congratulation 🎉 ! You have just completed the tenth JavaScript challenge.</h3><p>All of the above-written code is available on <a href="https://github.com/reitwiec/12DaysOfJS"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f994298e05d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/day-10-implementing-typeahead-search-f994298e05d1">Day 10— Implementing Typeahead Search</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 9— Event bubbling in real life?]]></title>
            <link>https://medium.com/iecse-hashtag/day-9-event-bubbling-in-real-life-3929441ac50a?source=rss-53b026960d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/3929441ac50a</guid>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[fundamentals]]></category>
            <category><![CDATA[ux]]></category>
            <dc:creator><![CDATA[Reitwiec Shandilya]]></dc:creator>
            <pubDate>Sun, 22 Dec 2019 08:16:10 GMT</pubDate>
            <atom:updated>2019-12-22T08:54:06.322Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learning how to actually use event bubbling in real life</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_hOWkH_0cHLNet83pn0B-Q.png" /></figure><h3>The 12 Days of JS?</h3><blockquote><strong><em>12 Days of JS</em></strong><em> is a series where we will tackle a new problem every day leading to Christmas, and solve it with the help of JavaScript ❤️. </em><strong><em>This isn’t a JavaScript 101 course</em></strong><em> but a way to improve the application of JavaScript in your projects! We aim to learn by application — encountering many new situations while talking about the hows, the whys and the whats we use to solve them.</em></blockquote><h4>Even wondered how you could improve the performance of your website with the help of event bubbling?</h4><blockquote>Well today, we’ll breakdown this slightly advanced topic of JavaScript!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*Ld8OxIW4Djmw_XwD.png" /><figcaption>Credits: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Whitespace_in_the_DOM">MDN Docs</a></figcaption></figure><p><em>Before we start I just want to point out that I’m using some ES6 features like </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const"><em>const</em></a><em> and </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let"><em>let</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions"><em>arrow functions</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla"><em>etc.</em></a><em> If you are not familiar with those, check the provided links to learn more.</em></p><h3>What is Event Bubbling?</h3><p>In simple terms, it’s the bubbling of an <strong>event up through the DOM tree</strong>.</p><p>To elaborate it further, I have a basic setup of an app where you can <strong>add</strong> and <strong>delete</strong> items.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FoNgWjwe%3Fheight%3D600%26slug-hash%3DoNgWjwe%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FoNgWjwe&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd8331a402b13979f8c06e5450b990d2/href">https://medium.com/media/fd8331a402b13979f8c06e5450b990d2/href</a></iframe><h4>Let’s see how this is working</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3885ddc0a6ee2bd0c5dc8b27c3fd516b/href">https://medium.com/media/3885ddc0a6ee2bd0c5dc8b27c3fd516b/href</a></iframe><p>So what we have done here is, with the help of the querySelectorAll() method, we have a NodeList() with references to all the <strong>buttons </strong>present in our list . We use these buttons to remove that particular item.</p><p>Then I used the forEach() method to attach an <strong>event</strong> to each button. The event that we want to listen for is the <strong>click</strong> event.</p><h4>This is where Event Bubbling comes into the picture.</h4><p>As soon as we click the button, event bubbling occurs without you necessarily knowing. It always occurs, unless you prevent it.</p><p>So when we click the button, the event is originated here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKxxQTniBJdFCEemyNzbOg.png" /></figure><p>Since we have an <strong>event listener</strong> added to this element, as soon as we click that button a callback function associated with that event listener is executed. What happens next is that the <strong>event bubbles</strong> up to its parent element. In this case it’s the li tag.</p><p>Now, if we were to have an <strong>event listener</strong> added to the li tags, then the callback functions for this would fire as well. So if we were to say,</p><pre>li.<strong>addEventListener</strong>(&#39;<strong>click</strong>&#39;, <strong>callbackFunction</strong>(){</pre><pre><strong>alert</strong>(&quot;hello world&quot;);</pre><pre>})</pre><p>then the event would bubble up and when it reached the li element, it will show an <strong>alert</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*h1GMJa1OyXluRBrVmd2MoA.gif" /><figcaption>Check it out here!</figcaption></figure><p>Similarly, after the li element, the event <strong>bubbles</strong> up to the ul and this continues till the furthermost parent element.</p><h3>With the help of this knowledge, we can solve one of our problems</h3><p>What we are doing currently is taking references to all the read it buttons and then adding an <strong>event listener</strong> of event type <strong>click</strong> to them.</p><blockquote>But what happens if we add a <strong>new element to the DOM</strong> and <strong>then</strong> try to <strong>remove it</strong>?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Hh3DQuf5TZd2_E_PYNW0RQ.gif" /></figure><h4>You see, we aren’t able to remove it. Can you guess why?</h4><p>It&#39;s because we have <strong>already associated</strong> the event listeners to each of the original buttons and not to the new ones.</p><p>Another drawback of our current implementation is that if we have a lot of buttons, then the task for assigning <strong>event listeners</strong> to each button would be very <strong>expensive</strong>.</p><h3>So how do we solve this?</h3><p>Ideally, we could attach an event listener to the ul element and wait for the click event to occur, and then the <strong>event will bubble up</strong> to the ul , and as soon as it reaches the ul element, we could find out the target which was originally clicked and then we can delete that li associated with that button.</p><h3>Let’s implement it</h3><p>First thing that I am going to do, is to get the reference to the ul element that consists of all the li element. I will do this with the help of the querySelector() method.</p><pre>const <strong><em>list</em></strong> = document.<strong>querySelector</strong>(&#39;<strong>#challenge-list ul</strong>&#39;)</pre><p>Once we have the reference to our ul element, we can just add an <strong>event listener</strong> of event type <strong>click</strong> to it.</p><p>list.<strong>addEventListener</strong>(<strong>&#39;click&#39;, removeIt</strong>)</p><p>Here the callback function is named removeIt .</p><p>Now, with the help of the event e available to us, we can get the target element.</p><pre>function <strong>removeIt</strong>(<strong>e</strong>){</pre><pre>console.log(<strong>e.target</strong>)</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QUr0RXL_JWOLxxICb9bBCQ.gif" /></figure><p>Now, our button has a class of read which we can use to filter out the clicks on the buttons from the rest of the clicks.</p><pre>if(e.<strong>target</strong>.<strong>className</strong> === &#39;<strong>read</strong>&#39;){</pre><pre>... do something here</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*mJF_qYUhwjH1m52gxB0PMg.png" /></figure><p>Now, the <strong>parent</strong> element of the <strong>button</strong> is a li and we essentially want to <strong>remove</strong> that entire li element.</p><p>With the help of the <strong>parentElement</strong> property, we can get the reference to the parent element of the button.</p><pre>if(e.<strong>target</strong>.<strong>className</strong> === &#39;<strong>read</strong>&#39;){</pre><pre>const <strong>li</strong> = e.<strong>target</strong>.<strong>parentElement</strong></pre><pre>}</pre><p>Now, we just need to remove this li element.</p><p>On checking the parent of this li element, we’ll notice that it’s the ul element whose reference is stored in the list variable. We can&#39;t then make use of the removeChild() method, and delete the li element.</p><pre>if(e.<strong>target</strong>.<strong>className</strong> === &#39;<strong>read</strong>&#39;){</pre><pre>const <strong>li</strong> = e.<strong>target</strong>.<strong>parentElement</strong></pre><pre><em>list</em>.<strong>removeChild</strong>(<strong>li</strong>)</pre><pre>}</pre><h3>And now, it should behave exactly like before, except now, we can also remove the newly added elements!</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FpovPjqj%3Fheight%3D600%26slug-hash%3DpovPjqj%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FpovPjqj&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/58744e27d6fd76cbffcbfe3f9347903e/href">https://medium.com/media/58744e27d6fd76cbffcbfe3f9347903e/href</a></iframe><h3>Congratulation 🎉 ! You have just completed the ninth JavaScript challenge and have made your website faster than it was before.</h3><p>All of the above-written code is available on <a href="https://github.com/reitwiec/12DaysOfJS"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3929441ac50a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/day-9-event-bubbling-in-real-life-3929441ac50a">Day 9— Event bubbling in real life?</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 8— A really slick navbar!]]></title>
            <link>https://medium.com/iecse-hashtag/day-8-a-really-slick-navbar-e3480932ef1a?source=rss-53b026960d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3480932ef1a</guid>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[user-interface]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Reitwiec Shandilya]]></dc:creator>
            <pubDate>Sat, 21 Dec 2019 06:36:49 GMT</pubDate>
            <atom:updated>2019-12-21T07:38:11.184Z</atom:updated>
            <content:encoded><![CDATA[<h4>Making a follow along dropdown</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3GT0OMN_GCN_50Rt-F7CQ.png" /></figure><h3>The 12 Days of JS?</h3><blockquote><strong>12 Days of JS</strong> is a series where we will tackle a new problem <em>every day</em> leading to Christmas, and solve it with the help of JavaScript ❤️. <strong>This isn’t a JavaScript 101 course</strong> but a way to improve the application of JavaScript in your projects! We aim to learn by application — encountering many new situations while talking about the hows, the whys and the whats we use to solve them.</blockquote><h3>Today we’ll try to replicate the functioning of this amazing navigation bar</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*y2cWv_ayhvLVIYeywMvNnQ.gif" /><figcaption>Credits: <a href="https://stripe.com/en-in">https://stripe.com/en-in</a></figcaption></figure><p><em>Before we start I just want to point out that I’m using some ES6 features like </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const"><em>const</em></a><em> and </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let"><em>let</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions"><em>arrow functions</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla"><em>etc.</em></a><em> If you are not familiar with those, check the links provided to learn more.</em></p><h3>Basic Setup</h3><p>Here is the breakdown of our initial setup without any JavaScript implemented</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FxxbqQbE%3Fheight%3D600%26slug-hash%3DxxbqQbE%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FxxbqQbE&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/5be49c7a1348f792f43002514ab7e9b6/href">https://medium.com/media/5be49c7a1348f792f43002514ab7e9b6/href</a></iframe><p>At the top, we have a <strong>nav</strong> element with a class top . This is followed by a div with the class dropdownBackground , and this is that white background of the dropdown that will reshape itself based on the content in the drop down and it’ll follow us wherever we move on the navbar.</p><p>Then we have an<strong> unordered list</strong> with a class cool and that contains our <strong>list </strong>items which are our options available in the navbar.</p><p>Now, the important thing to note here is, that the top level li will be our triggers. <strong>Why?</strong> If we make the anchor tag as our trigger element, then if we enter the drop down, we’ll be hovering off the a tag and that will trigger the off state.</p><p>You’ll understand all of this a lot better once we start making it functional.</p><p>In terms of CSS, it’s pretty straightforward and is just used to make the page look pretty.</p><h4>Now that we have our basic setup ready, let’s start adding some JavaScript!</h4><h3>Triggered!</h3><p>Our first step would be to get our trigger elements that’ll set off the dropdown menu, these trigger elements are the options available in the navbar.</p><p>We’ll get the references to these triggers with the help of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll">querySelectorAll()</a> method. If you’ve been following the series, you must be familiar with it by now.</p><pre>const <strong><em>triggers</em></strong> = document.<strong>querySelectorAll</strong>(&#39;<strong>.cool &gt; li</strong>&#39;)</pre><p>This will return a <a href="https://developer.mozilla.org/en-US/docs/Web/API/NodeList"><strong>NodeList</strong></a> with all the navbar options in it.</p><h4>Then we also need to grab that dropdown background.</h4><pre>const <strong><em>background</em></strong> = document.<strong>querySelector</strong>(&#39;<strong>.dropdownBackground</strong>&#39;)</pre><p>Along with this, let’s also bring in the <strong>nav</strong>.</p><pre>const <strong><em>nav</em></strong> = document.<strong>querySelector</strong>(&#39;<strong>.top</strong>&#39;)</pre><h3>Listen to me!</h3><p>Now, once we have all the references, let’s somehow listen to<strong> hover-in</strong> and <strong>hover-out</strong> on the navbar options, so that we are able to do the cool stuff.</p><p>I will make <strong>two functions</strong> here to handle the situations when the <strong>user enters </strong>the hover state and when the <strong>user leaves </strong>the hover state.</p><pre>function <strong>handleEnter</strong>(){</pre><pre>}</pre><pre>function <strong>handleLeave</strong>(){</pre><pre>}</pre><p>With the help of <strong>event listeners</strong> of type <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event"><strong>mouseenter</strong></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event"><strong>mouseleave</strong></a>, we’ll manipulate the navbar.</p><pre><strong>triggers</strong>.forEach(<strong>trigger</strong> =&gt; <strong>trigger</strong>.<strong>addEventListener</strong>(&#39;<strong>mouseenter</strong>&#39;, <strong>handleEnter</strong>))</pre><pre><strong>triggers</strong>.forEach(<strong>trigger</strong> =&gt; <strong>trigger</strong>.<strong>addEventListener</strong>(&#39;<strong>mouseleave</strong>&#39;, <strong>handleLeave</strong>))</pre><p>Let’s just now make sure that our functions are working properly.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FMWYpzBy%3Fheight%3D600%26slug-hash%3DMWYpzBy%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FMWYpzBy%3Feditors%3D1111&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fdf31fd33efbabb8eeda28cb68e4b03/href">https://medium.com/media/6fdf31fd33efbabb8eeda28cb68e4b03/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*oeV-MBZ_Wgp0tNPTwfRh-w.gif" /><figcaption>And…. it’s working!</figcaption></figure><p><strong>We’ll now divide the remaining stuff into two parts:</strong></p><ol><li>Display the contents of the dropdown.</li><li>Place and resize our dropdown background according to the content.</li></ol><h3><strong>Part 1</strong></h3><p>Now the way we’re going to do that is by <strong>adding and removing</strong> classes when it hovers in and when it hovers out respectively. And then with the help of those classes, we’ll <strong>change the CSS </strong>of the dropdown contents.</p><p>So when the user hovers in</p><pre>function <strong>handleEnter</strong>() {</pre><pre>this.<a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/classList"><strong>classList</strong></a>.<strong>add</strong>(&quot;<strong>trigger-enter-display</strong>&quot;);</pre><pre><strong>setTimeout</strong>(() =&gt;this.<strong>classList</strong>.<strong>add</strong>(&quot;<strong>trigger-enter- visible</strong>&quot;),<strong>150</strong>);</pre><pre>}</pre><p>You must’ve noticed the <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout">setTimeout()</a> function that I’ve used. You’ll see the reason for adding that below.</p><p>I will now add some CSS in our <strong>trigger-enter-display </strong>class and <strong>trigger-enter- visible </strong>class.</p><p>If you checkout the CSS of <strong>dropdown</strong>, you’ll notice that it has display:none and opacity:0 . Now, we could change both at the same time in the same class, but since we need a nice transition we’ll do something like this</p><pre>.<strong>trigger-enter-display .dropdown</strong>{</pre><pre><strong><em>display</em> : block</strong>;</pre><pre>}</pre><pre>.<strong>trigger-enter-visible .dropdown</strong>{</pre><pre><strong><em>opacity</em> : 1</strong>;</pre><pre>}</pre><p>Let’s also remove these classes when the user hovers off.</p><pre>function <strong>handleEnter</strong>() {</pre><pre>this.<strong>classList</strong>.<strong>remove</strong>(&quot;<strong>trigger-enter-display</strong>&quot;,&quot;<strong>trigger-enter-visible</strong>&quot;);</pre><pre>}</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FExaWOzw%3Fheight%3D600%26slug-hash%3DExaWOzw%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FExaWOzw&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6aa793961636e5c051f71f122f22e95/href">https://medium.com/media/d6aa793961636e5c051f71f122f22e95/href</a></iframe><p>Now, you must be thinking that we could’ve done the exact same thing with just a few lines of CSS, <strong>why did use JavaScript for this?</strong></p><p>You’ll find the answer to that question in part 2 below!</p><h3>Part 2</h3><p>We already have the reference to the dropdown background stored in a variable called background .</p><p>So let’s just go and make it visible whenever we hover in. We will again do this by adding a class to it. I will call this class open .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fee462f1eec268eb85a0c3eab9fe6c3/href">https://medium.com/media/6fee462f1eec268eb85a0c3eab9fe6c3/href</a></iframe><pre>.<strong>dropdownBackground</strong> .<strong>open</strong>{</pre><pre>    <strong><em>opacity</em> </strong>: <strong>1</strong>;</pre><pre>}</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FrNayoNz%3Fheight%3D600%26slug-hash%3DrNayoNz%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FrNayoNz&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b4fb65b4ab3c72270011200d3a19b2a/href">https://medium.com/media/9b4fb65b4ab3c72270011200d3a19b2a/href</a></iframe><h3>Now we need to do the real heavy-lifting</h3><p>Okay, now we need to find out the following things:</p><ul><li><strong>How high is the dropdown content?</strong></li><li><strong>How wide is the dropdown content?</strong></li><li><strong>Where on the page does the dropdown content live?</strong></li></ul><p>First thing we need to figure out which dropdown it actually is.</p><pre>function <strong>handleEnter</strong>(){</pre><pre>....some code here</pre><pre>const <strong><em>dropdown</em></strong> = this.<strong>querySelector</strong>(&#39;<strong>.dropdown</strong>&#39;);</pre><pre>}</pre><p>So, we’re looking for a <strong>dropdown</strong> that<strong> lives inside the trigger </strong>we have hovered on, that is why we have used this and not document.</p><p>JavaScript provides us with a method called <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect"><strong>getBoundingClientRect()</strong></a> . Now that sounds scary. What that method allows us to do is, get the co-ordinates of an HTML element on the document in terms of <strong>viewport coordinates.</strong></p><pre>const <strong>dropdownCords</strong> = dropdown.<strong>getBoundingClientRect</strong>()</pre><p>Now if I console log it, this is what I get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ZmEbzeGatsrMWQqHSDM2iQ.png" /></figure><p>Here is where the magic happens!</p><p>Let’s just make an object and store all the required details in it.</p><pre>const <strong>cords</strong> = {</pre><pre><strong>height</strong>: dropdownCords.height,</pre><pre><strong>width</strong>: dropdownCords.width,</pre><pre><strong>top</strong>: dropdownCords.top,</pre><pre><strong>left</strong>: dropdownCords.left</pre><pre>}</pre><p>Now, since we have the reference to our dropdown background in background , I can just go ahead and change it’s CSS properties.</p><pre>background.style.<strong>setProperty</strong>(&#39;<strong>width</strong>&#39;,`${<strong>cords.width</strong>}px`);</pre><pre>background.style.<strong>setProperty</strong>(&#39;<strong>height</strong>&#39;,`${<strong>cords.height</strong>}px`);</pre><pre>background.style.setProperty(&#39;<strong>transform</strong>&#39;,`<strong>translate</strong>(${<strong>cords.left</strong>}px,${<strong>cords.top</strong>}px)`);</pre><h3>And we are done!</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FvYExvXM%3Fheight%3D600%26slug-hash%3DvYExvXM%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FvYExvXM&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d3f91267fc73d1adf7ba196cbc6038e/href">https://medium.com/media/4d3f91267fc73d1adf7ba196cbc6038e/href</a></iframe><p>Or wait...</p><p>Something seems wrong here.</p><p><strong>Can you try and think for a minute as to why that is happening?</strong></p><h3>Here is why</h3><p>If you notice, the navbar is not the first element on the document there is a h tag above it. So because of that, our viewport coordinates are pushed below the value they’re supposed to be.</p><p>So to solve this problem, we can get the coordinates of the navbar, and then <strong>subtract</strong> the top of the navbar from the <strong>dropdown top</strong>, and subtract the left of the navbar from the <strong>dropdown left</strong>.</p><pre>const <strong>navCords</strong> = nav.<strong>getBoundingClientRect</strong>();</pre><pre>const <strong>cords</strong> = {</pre><pre>....</pre><pre><strong><em>top</em></strong>: dropdownCords.<strong>top</strong> - navCords.<strong>top</strong>,</pre><pre><strong><em>left</em></strong>: dropdownCords.<strong>left</strong> - navCords.<strong>left</strong></pre><pre>};</pre><p>It should work beautifully now.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FJjoWwax%3Fheight%3D600%26slug-hash%3DJjoWwax%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FJjoWwax&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/63c484f9bdc8b46afe85f9252201733c/href">https://medium.com/media/63c484f9bdc8b46afe85f9252201733c/href</a></iframe><h3>How can this be improved?</h3><ul><li>When you swiftly hover over the navbar options, there is a glitch that the text shows up before the dropdown box.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*EK_6cXrZlXRDW4XyJ7HQtw.gif" /></figure><p>I’ve given the solution in the end.</p><ul><li>Use visibility: hidden and pointer-events: none instead of display:none. This means you don’t need the -visible class as these properties are toggles, with the opacity taking care of the transition effect. This also means, you can pre-cache the getBoundingClientRect() coords.</li></ul><p>There are a lot more things that can be improved and added. Let us know about your ideas in the responses below!</p><h3>Solution for that glitch</h3><p>If you remember our setTimeout() method that we were using, there we were displaying the text 150ms after we hover over it. Now what happened is, because of us hover so swiftly, the method got triggered and before 150ms got over, we were already hovering on some other option. This cause the delay that we saw.</p><p>We just need to make a small change to fix this</p><pre><strong>setTimeout</strong>(() =&gt; {</pre><pre><strong>if</strong> (this.classList.<strong>contains</strong>(&quot;<strong>trigger-enter-display</strong>&quot;)) {</pre><pre>this.classList.<strong>add</strong>(&quot;<strong>trigger-enter-visible</strong>&quot;);</pre><pre>}</pre><pre>}, 150);</pre><p>So we’re only making the content visible, if we’re still hovering over the same option by the end of 150ms.</p><h3>Congratulation 🎉 ! You have just completed the second JavaScript challenge and have become an expert at adding Easter-Eggs.</h3><p>All of the above-written code is available on <a href="https://github.com/reitwiec/12DaysOfJS"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3480932ef1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/day-8-a-really-slick-navbar-e3480932ef1a">Day 8— A really slick navbar!</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 7— Nobody can drag me]]></title>
            <link>https://medium.com/iecse-hashtag/day-7-nobody-can-drag-me-dda9ed8dc041?source=rss-53b026960d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/dda9ed8dc041</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[user-experience]]></category>
            <dc:creator><![CDATA[Reitwiec Shandilya]]></dc:creator>
            <pubDate>Fri, 20 Dec 2019 07:27:52 GMT</pubDate>
            <atom:updated>2019-12-20T07:27:52.193Z</atom:updated>
            <content:encoded><![CDATA[<h4>Making a click and drag slider</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1kI2jFby5uRsvAmtjDgr_g.png" /></figure><h3>The 12 Days of JS?</h3><blockquote><strong>12 Days of JS</strong> is a series where we will tackle a new problem <em>every day</em> leading to Christmas, and solve it with the help of JavaScript ❤️. <strong>This isn’t a JavaScript 101 course</strong> but a way to improve the application of JavaScript in your projects! We aim to learn by application — encountering many new situations while talking about the hows, the whys and the whats we use to solve them.</blockquote><h3>Today we’ll be implementing a click and drag scroll to our usual horizontal scrolling element.</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl46CpQCMebfMmnPq0%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl46CpQCMebfMmnPq0%2Fsource.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl46CpQCMebfMmnPq0%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/4154b57105850576dacbbc62805344b5/href">https://medium.com/media/4154b57105850576dacbbc62805344b5/href</a></iframe><p><em>Before we start I just want to point out that I’m using some ES6 features like </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const"><em>const</em></a><em> and </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let"><em>let</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions"><em>arrow functions</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla"><em>etc.</em></a><em> If you are not familiar with those, check the provided links to learn more.</em></p><h3>Basic Setup</h3><p>Here is a breakdown of our boilerplate that we’ll be using today</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FxxbgrWW%3Fheight%3D600%26slug-hash%3DxxbgrWW%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FxxbgrWW&amp;image=https%3A%2F%2Fscreenshot.codepen.io%2F2967318.xxbgrWW.small.f5138686-0eae-44c9-a557-0fc47f93208e.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7932035bf600d4fc72398a3259dea60/href">https://medium.com/media/f7932035bf600d4fc72398a3259dea60/href</a></iframe><p>The setup is pretty straightforward. There is one big items div that has smaller item divs. The overflow-x property of items is set to <strong>scroll</strong>, and overflow-y is set to <strong>hidden</strong>.</p><p>Now that our basic setup is ready, we can start adding JavaScript to it!</p><h3>Grabbing elements</h3><p>Lets first quickly get all the references to the HTML elements that we would required for our purpose.</p><p>For this challenge, we only need to get the big items div which is our <strong>slider</strong>, because all of our <strong>mouse-events</strong> and manipulation will happen only on the slider.</p><p>With the help of the querySelector() method, we can get the reference to items and store it in some variable called <strong>slider</strong>.</p><pre>const <strong><em>slider</em></strong> = document.<strong>querySelector</strong>(&quot;<strong>.items</strong>&quot;);</pre><h3>What are mouse events?</h3><p>These are events that occur due to the user interacting with a pointing device (such as a mouse).</p><p>We’ll be looking at four <a href="https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent">mouse events</a> today: mousedown, mouseleave, mouseup and mousemove.</p><ul><li>mousedown - fired at an <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element">Element</a> when a pointing device button is pressed while the pointer is inside the element.</li><li>mouseleave - fired at an <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element">Element</a> when the cursor of a pointing device (usually a mouse) is moved out of it.</li><li>mouseup - fired at an <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element">Element</a> when a button on a pointing device (such as a mouse or trackpad) is released while the pointer is located inside it.</li><li>mousemove - fired at an element when a pointing device (usually a mouse) is moved while the cursor’s hotspot is inside it.</li></ul><p>So we’ll be adding all of the above events to our slider as an <strong>event listener</strong>.</p><pre>slider.<strong>addEventListener</strong>(&quot;<strong>mousedown</strong>&quot;, <strong>e</strong> =&gt; {});</pre><pre>slider.<strong>addEventListener</strong>(&quot;<strong>mouseleave</strong>&quot;, () =&gt; {});</pre><pre>slider.<strong>addEventListener</strong>(&quot;<strong>mouseup</strong>&quot;, () =&gt; {});</pre><pre>slider.<strong>addEventListener</strong>(&quot;<strong>mousemove</strong>&quot;, <strong>e</strong> =&gt; {});</pre><h3>Going down</h3><p>Let’s declare a flag to keep track of whether our mouse is down or not. I will call that flag isDown and initialize it to false.</p><p>Now when the mousedown event occurs I want to change the isDown flag to true, and when mouseleave or mouseup event occurs, I will change it back to false .</p><p>Since the value of the variable is changing, we’ll declare it as let .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d12bafe320b02d259965dffb2bb02151/href">https://medium.com/media/d12bafe320b02d259965dffb2bb02151/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LjVX84eX38Ye7Nwc3NBl8Q.gif" /></figure><p>As you can see, it’s logging like crazy right. Now, I don’t want it to do anything if isDown is false.</p><p>So we can tweak the function a little bit</p><pre>slider.<strong>addEventListener</strong>(&quot;<strong>mousemove</strong>&quot;, <strong>e</strong> =&gt; {</pre><pre>    if (!<strong>isDown</strong>) <strong>return</strong>;</pre><pre>    console.log(&quot;<strong>Do work here</strong>!&quot;);</pre><pre>});</pre><p>So if isDown is false , it won’t do anything and will just return.</p><p>(<strong>!Optional</strong>) I’ve made a little CSS which will allow us to see if the slider is active or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccca28bab505d060fdac28eae80e3083/href">https://medium.com/media/ccca28bab505d060fdac28eae80e3083/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FdyPvyZe%3Fheight%3D600%26slug-hash%3DdyPvyZe%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FdyPvyZe&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd6da9b2df3ad35c485f401c0a6ef3f6/href">https://medium.com/media/bd6da9b2df3ad35c485f401c0a6ef3f6/href</a></iframe><h3>Initial offset</h3><p>Our next step would be to know where the user’s first click is in the slider. Knowing that initial position will help us find out how far left or how far right we have to scroll the div. Let’s do this step by step.</p><p>To store the initial position of the user’s click, I will declare a variable called startX. I will again declare it as a let since we will be changing the its value often.</p><pre>let <strong>startX</strong>;</pre><p>Now, whenever the <strong>mousedown</strong> <strong>event</strong> occurs, I want to set the cursor’s position at that <strong>moment</strong> to the variable startX.</p><p>The <strong>mouse event</strong> has a property called <a href="https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageX"><strong>pageX</strong></a><strong> </strong>that will give the position of out cursor.</p><p><strong>But, do you think that’s what we need?</strong> pageX will return the position <strong>with respect to the page</strong> and <strong>not the slider</strong>. Suppose our slider has a <strong>margin-left</strong> of <strong>25px</strong>, what we want is pageX — 25 and not just pageX .</p><p>Let’s try writing the code for it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97ba76f8966c53918a235554753a321a/href">https://medium.com/media/97ba76f8966c53918a235554753a321a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*oHLAcu-zs5CCKhyxY-8ERQ.gif" /><figcaption>click click click click</figcaption></figure><h3>An edge case</h3><h4>What if the user has already scrolled in a few pixels and then starts dragging?</h4><p>For that, we need to store the amount of scroll that is already present. I will store it in a variable called scrollLeft.</p><p>And the way we can get that amount is with the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft">scrollLeft</a> property of the slider.</p><pre><strong>scrollLeft</strong> = <em>slider</em>.<strong>scrollLeft</strong></pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2599fa1f9534fc34a2ea91fa53b5b62/href">https://medium.com/media/f2599fa1f9534fc34a2ea91fa53b5b62/href</a></iframe><h3>Lets do some magic</h3><p>Inside mousemove we need to monitor our cursor continuous and keep recalculating its position. Let’s store that position in a variable called x .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aad0d12b9e572db568b3e940c914e5f1/href">https://medium.com/media/aad0d12b9e572db568b3e940c914e5f1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Pk_-sPkYOCPOH0OiQiKmLQ.gif" /><figcaption>(x, startX)</figcaption></figure><p>Now, we can calculate how far we have deviated from our mouse click by making use of x and startX . To store calculated value, lets a use a variable called deviation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38c80ac8efbfcc549477f251e43434e1/href">https://medium.com/media/38c80ac8efbfcc549477f251e43434e1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*1LRs0CqPBYTWmdpK_-Pn4Q.gif" /></figure><p><strong>Next what we have to do is to actually scroll the div.</strong></p><p>Here, we will use the <strong>scrollLeft</strong> property of the slider to make it scroll.</p><pre>slider.<strong>scrollLeft</strong> = <strong>scrollLeft</strong> - <strong>deviation</strong>;</pre><p>And we’re done!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FvYExEXo%3Fheight%3D600%26slug-hash%3DvYExEXo%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FvYExEXo&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/754e4c54210097b44090883d713b7cea/href">https://medium.com/media/754e4c54210097b44090883d713b7cea/href</a></iframe><h3>Things that can be improved</h3><p>Something called <strong>intertial scrolling</strong> can be added to it. With this you can just flick and replicate the property of <strong>intertia</strong>. This involves a little <strong>physics</strong> and <strong>a lot of math</strong>.</p><p>Here is an example of intertial scrolling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*eSJy3x6NRYFi52n-Ls8gaw.gif" /><figcaption>Credits: <a href="https://hoverstat.es/">https://hoverstat.es/</a></figcaption></figure><h4>Congratulation 🎉 ! You have just completed the seventh JavaScript challenge.</h4><p>All of the above-written code is available on <a href="https://github.com/reitwiec/12DaysOfJS"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dda9ed8dc041" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/day-7-nobody-can-drag-me-dda9ed8dc041">Day 7— Nobody can drag me</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 6 — I’m really strong and I’m... sticky!]]></title>
            <link>https://medium.com/iecse-hashtag/day-6-im-really-strong-and-i-m-sticky-cea10b9cd80a?source=rss-53b026960d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/cea10b9cd80a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[fundamentals]]></category>
            <dc:creator><![CDATA[Reitwiec Shandilya]]></dc:creator>
            <pubDate>Thu, 19 Dec 2019 06:24:31 GMT</pubDate>
            <atom:updated>2019-12-19T06:24:31.150Z</atom:updated>
            <content:encoded><![CDATA[<h3>Day 6 — I’m really strong and I’m... sticky!</h3><h4>Making a sticky navigation bar</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8k_yjojxstfMqo7dXX0RA.png" /></figure><h3>The 12 Days of JS?</h3><blockquote><strong><em>12 Days of JS</em></strong><em> is a series where we will tackle a new problem every day leading to Christmas, and solve it with the help of JavaScript ❤️. </em><strong><em>This isn’t a JavaScript 101 course</em></strong><em> but a way to improve the application of JavaScript in your projects! We aim to learn by application — encountering many new situations while talking about the hows, the whys and the whats we use to solve them.</em></blockquote><h4>Today we will learn how to make a navbar stick to the top of your website when you scroll over it!</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FBWD3CtcudWL28%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FBWD3CtcudWL28%2Fsource.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FBWD3CtcudWL28%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="305" frameborder="0" scrolling="no"><a href="https://medium.com/media/1695cb62a46f165cf83df9aead99b8ab/href">https://medium.com/media/1695cb62a46f165cf83df9aead99b8ab/href</a></iframe><h3>Basic Setup</h3><p>To concentrate more on the JavaScript aspect of our challenge, I’ve already made a simple site with basic HTML and CSS for all of you.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FoNgzJgN%3Fheight%3D600%26slug-hash%3DoNgzJgN%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FoNgzJgN&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/00c7e3d9ebea67d12f48434db34cba4b/href">https://medium.com/media/00c7e3d9ebea67d12f48434db34cba4b/href</a></iframe><p>The above site is really straightforward, it is split into <strong>3 parts</strong>: header , navbar and a div with some content.</p><h4>Let’s start adding some JavaScript now!</h4><h3>Getting the navbar into the script</h3><p>If you have a look at the HTML code, our navbar has an <strong>ID</strong> main added to it.</p><p>Now, we can use the selector(ID) to get a reference to the navbar with the help of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector">querySelector()</a> method.</p><p>Let’s <strong>store</strong> the <strong>reference</strong> in a <strong>variable</strong> called nav .</p><pre>const <strong><em>nav</em></strong> = document.<strong>querySelector</strong>(&#39;<strong>#main</strong>&#39;);</pre><p>If we log the value of nav to the console we can checkout the reference</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*UwYvKCmEslvku09qbJlIPQ.png" /></figure><h3>Keep Scrolling</h3><p><strong>Let’s think about what we are try to achieve here.</strong> Whenever the <strong>user</strong> is <strong>scrolling</strong> and the <strong>top of the window</strong> touches the <strong>top of the navbar</strong>, we want to <strong>fix</strong> the <strong>navbar</strong> to that position. And if the <em>top of the window</em> again goes over the <em>top of the navbar</em>, we want it to go back to its <strong>original position</strong>.</p><p>So, we need to find a way to keep monitoring our window location while we <strong>scroll</strong>. This means, we the <strong>event</strong> we need to <strong>listen</strong> for is the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scroll_event">scroll event</a>.</p><p>With the help of the addEventListener() method, we can make our <strong>window</strong> listen to a scroll event.</p><p>To handle the event, lets make a function called <strong>fixingNav()</strong>.</p><p>If we want to check how far down we have scrolled, <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window">window</a> has a property called <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY">scrollY</a> that we can use to find it.</p><pre>function <strong><em>fixingNav</em></strong>(){</pre><pre>     console.<strong>log</strong>(window.<strong>scrollY</strong>);</pre><pre>}</pre><pre>window.<strong>addEventListener</strong>(&#39;<strong>scroll</strong>&#39;,<strong>fixingNav</strong>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Fb9LHDH-flvYrByKimbXJg.gif" /></figure><p><strong>You probably have guessed what our next step would be.</strong></p><p>We need to find out how far down the navbar is placed from the top of the document.</p><p>A reference to the <strong>navbar</strong> is stored in the variable nav. <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement"><strong>HTMLElement</strong></a> has a property of <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop">offsetTop</a>, that gives us how far down an html element is from the top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7OTT_2FV-GdkaQYLdasrgQ.gif" /><figcaption>Checking how far we have scrolled and how far down the navbar’s position is</figcaption></figure><p>Let’s store the position of nav in some variable fromTop .</p><pre>const <strong>fromTop</strong> = nav.<strong>offsetTop</strong>;</pre><h3>Fix it!</h3><p>So now, when window.scrollY become greater than or equal to nav.offsetTop we want to fix our navbar to the top.</p><p>One way of doing it would be to check if window.scrollY is more than fromTop , if it is, we want to change the CSS of our navbar.</p><p>What we will do is <strong>add a new class</strong> to the <strong>body</strong> as soon as the above condition becomes <strong>true</strong>, and if it become <strong>false</strong>, we will <strong>remove that class</strong>.</p><p>We will make use of <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/classList">classList</a> property of an element to add a new class to the existing ones.</p><pre>if(window.<strong>scrollY</strong> &gt;= <strong>fromTop</strong>){</pre><pre>    window.<strong>body</strong>.<strong>classList</strong>.<strong>add</strong>(&quot;<strong>fixed-nav</strong>&quot;);</pre><pre>}else{</pre><pre>    window.<strong>body</strong>.<strong>classList</strong>.<strong>remove</strong>(&quot;<strong>fixed-nav</strong>&quot;);</pre><pre>}</pre><p>Then, we will add some CSS to change the <strong>position</strong> of the navbar.</p><pre><strong><em>.fixed-nav nav</em></strong>{<br>   <br>    position: <strong>fixed</strong>;</pre><pre>}</pre><h4><strong>Why are we adding a class to the body and not directly to the navbar?</strong></h4><p>The only reason why we are doing this is so that we can <strong>access any</strong> of the <strong>children</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lliaPt6Gw-lteClqf8F8eg.gif" /></figure><p>But if you notice, as soon as we reach the top of the navbar, the div below <strong>suddenly jumps</strong>. The reason for that is, when we make the navbar fixed, it no longer takes <strong>space in the document</strong>, and it float on top. This causes a <a href="https://stackoverflow.com/questions/27637184/what-is-dom-reflow">reflow</a> on the page, and it moves up the exact amount of space the <strong>height</strong> of the navbar is.</p><p>So to solve this, we need to offset the body by that amount.</p><p>To get the <strong>height</strong> of the <strong>navbar</strong>, we can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight">offsetHeight</a> , and to add the <strong>padding</strong> to the body we can change the style by changing the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Properties_Reference">paddingTop</a> property of the body.</p><pre>if (window.<strong>scrollY</strong> &gt;= <strong>fromTop</strong>) {</pre><pre>    document.<strong>body</strong>.<strong>style</strong>.<strong>paddingTop</strong> = nav.<strong>offsetHeight</strong> + &quot;<strong>px</strong>&quot;;</pre><pre>    document.<strong>body</strong>.<strong>classList</strong>.add(&quot;<strong>fixed-nav</strong>&quot;);</pre><pre>} else {</pre><pre>    document.<strong>body</strong>.<strong>style</strong>.<strong>paddingTop</strong> = 0;</pre><pre>    document.<strong>body</strong>.<strong>classList</strong>.<strong>remove</strong>(&quot;<strong>fixed-nav</strong>&quot;);</pre><pre>}</pre><p>The reason why we have added &quot;px&quot; with nav.offsetHeight is because nav.offsetHeight gives us the height as a <strong>number</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FKKwgbjE%3Fheight%3D600%26slug-hash%3DKKwgbjE%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FKKwgbjE&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/28d5a434c3ef198560e73ed9e3889946/href">https://medium.com/media/28d5a434c3ef198560e73ed9e3889946/href</a></iframe><h3>EXTRA EXTRA EXTRA!</h3><p>If you check out the <strong>HTML</strong> for the <strong>navbar</strong> you can see there is a list item which has a <strong>logo image</strong>, and if you check out the <strong>CSS</strong> of it, you’ll see that it has a max-width:0, and hence it’s <strong>not visible</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozJbBN0VCdTC4byDmAWrfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*ArofU_A8SCebeEXsfS-LLA.png" /></figure><p>Now we can also make it visible by changing the CSS a little.</p><pre>.<strong>fixed-nav</strong> li.<strong>logo</strong> {</pre><pre>  <strong>  max-width</strong>: <strong>500px</strong>;</pre><pre>}</pre><p>Try it out below!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FXWJjObm%3Fheight%3D600%26slug-hash%3DXWJjObm%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FXWJjObm&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/cad2786a2142a70464e48fcb9d9f8ddc/href">https://medium.com/media/cad2786a2142a70464e48fcb9d9f8ddc/href</a></iframe><p>You can play more with it and add more features to it, for example, increase the size of the content when the navbar sticks to the top.</p><h4>Congratulation 🎉 ! You have just completed the sixth JavaScript challenge.</h4><p>All of the above-written code is available on <a href="https://github.com/reitwiec/12DaysOfJS"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cea10b9cd80a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/day-6-im-really-strong-and-i-m-sticky-cea10b9cd80a">Day 6 — I’m really strong and I’m... sticky!</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 5— Refresh and poof, gone?]]></title>
            <link>https://medium.com/iecse-hashtag/day-5-refresh-and-poof-gone-50651ddf3fc?source=rss-53b026960d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/50651ddf3fc</guid>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[sessions]]></category>
            <category><![CDATA[localstorage]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Reitwiec Shandilya]]></dc:creator>
            <pubDate>Wed, 18 Dec 2019 07:23:02 GMT</pubDate>
            <atom:updated>2019-12-18T07:23:02.160Z</atom:updated>
            <content:encoded><![CDATA[<h3>Day 5— Refresh and *poof*, gone?</h3><h4>What the heck is local storage?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lF0NJ1RtNe-iaJ0vDY7NQw.png" /></figure><h3>The 12 Days of JS?</h3><blockquote><strong>12 Days of JS</strong> is a series where we will tackle a new problem <em>every day</em> leading to Christmas, and solve it with the help of JavaScript ❤️. <strong>This isn’t a JavaScript 101 course</strong> but a way to improve the application of JavaScript in your projects! We aim to learn by application — encountering many new situations while talking about the hows, the whys and the whats we use to solve them.</blockquote><h4>Ever wonder why your preferences on your website go away once you go to some other page, or refresh it? Or how, many websites store your changes temporarily for a certain amount of time?</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FXqpnXaeZPnupy%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FXqpnXaeZPnupy%2Fsource.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FXqpnXaeZPnupy%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dd7b635ddd8db5ae824e922608c2f92/href">https://medium.com/media/3dd7b635ddd8db5ae824e922608c2f92/href</a></iframe><h4>Well today, we will be demystifying the concept of browser storage, and try and understand local storage in detail.</h4><p><em>Before we start I just want to point out that I’m using some ES6 features like </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const"><em>const</em></a><em> and </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let"><em>let</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions"><em>arrow functions</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla"><em>etc.</em></a><em> If you are not familiar with those, check the provided links to learn more.</em></p><h3>Storages?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*SpeMPIzhuta7hWeZrE3Ulw.png" /><figcaption>Check out Application tab in your inspector</figcaption></figure><h4>Cookies vs Local Storage vs Session Storage</h4><p><strong>So what’s the difference between them?</strong> Well, they are all ways of storing data in the browser but here are the basic differences between them</p><h4>Capacity</h4><ul><li>Cookies: only stores <strong>4kb</strong> of data.</li><li>Local Storage: only stores <strong>10mb</strong> of data.</li><li>Session Storage: only stores <strong>5mb</strong> of data.</li></ul><blockquote>Now, Cookies are available in <strong>older browsers</strong>(HTML4, HTML5) as well, but Local Storage and Session Storage are <strong>only available</strong> in browsers that support HTML5.</blockquote><h4>Accessibility</h4><ul><li>Cookies: accessible from <strong>any window</strong>.</li><li>Local Storage: accessible from <strong>any window</strong>.</li><li>Session Storage: accessible from the <strong>same tab</strong>.</li></ul><h4>Expiration</h4><ul><li>Cookies: is <strong>manually set</strong>.</li><li>Local Storage: <strong>never</strong> expires.</li><li>Session Storage: expires on <strong>tab close</strong>.</li></ul><h4>Storage Location</h4><ul><li>Cookies: stored in the <strong>browser</strong> and the session ID that’s within a cookie is also stored in the <strong>server</strong>.</li><li>Local Storage: stored in the <strong>browser</strong>.</li><li>Session Storage: stored in the <strong>browser</strong>.</li></ul><blockquote>Cookies are sent to the server on every request. Whenever you load an image, load a css file or load an html file, they are sent to the server.</blockquote><p>So basically, Cookies are best for data that has to be <strong>accessed by the server and the local machine</strong>, or for something you want to <strong>set an expiration date</strong> <strong>on</strong>. Cookies are often used for something like <strong>authentication information</strong> that you have to be sending <strong>regularly back and forth</strong>.</p><p>As you can see, Local Storage and Session Storage are very similar and they only differ in their expiration. They are so similar that they even have the exact same methods associated with them.</p><h3>Diving deeper into Local Storage</h3><p>For the explanation of <strong>local storage</strong> I will take the code from our <strong>previous challenge</strong> and store our <strong>theme preference</strong> in our<strong> local storage</strong> somehow.</p><p>Here is the code from the previous challenge</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FvYEKaxY%3Fheight%3D600%26slug-hash%3DvYEKaxY%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FvYEKaxY&amp;image=https%3A%2F%2Fscreenshot.codepen.io%2F2967318.vYEKaxY.small.b139891b-ef6e-42cf-8e0d-bd0f3198d643.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d2e9198d9e01ff0541cd2a5ef0f85b9/href">https://medium.com/media/3d2e9198d9e01ff0541cd2a5ef0f85b9/href</a></iframe><p>If I go and click on <strong>Local Storage</strong> inside the <strong>Application</strong> tab of our <strong>inspector</strong>, you’ll notice that it is empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3eD49_CWoC399CNmN9p2Q.png" /></figure><p>There is a list for <strong>keys</strong> and a list for <strong>values</strong>. That’s what Local Storage is, a bunch of <strong>key-value</strong> pairs.</p><p>Now, the only <strong>limitation</strong> while inserting data is that, <strong>it has to be a string</strong>. That’s what’s gonna bring us to our <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON"><strong>JSON</strong></a> object. There is a JSON object in JavaScript, that allows us to convert <strong>stuff to string</strong>. Stuff like objects, arrays, boolean values and so on.</p><p>Alright, so let’s start with some <strong>basic things</strong> that we can do with localStorage.</p><p>Since <strong>Local Storage</strong> exists inside our window, we can just access it with localStorage .</p><h4>How to add items to the local storage?</h4><p>There is a setItem() method that will allow us to put our data into the local storage. It’ll ask for a (name, value) , basically the <strong>key</strong> and the <strong>value</strong>.</p><pre><strong><em>localStorage</em></strong>.setItem(&#39;<strong>patience</strong><em>&#39;,&#39;</em><strong>you must have, my young padawan</strong><em>&#39;</em>);</pre><p>If we check our local storage now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-_XROnspC4eqcLotJmFNbw.png" /></figure><p>Now, if I ever want to retrieve this, I can just use the method getItem(<strong>key</strong>) .</p><pre>let <strong><em>yoda</em></strong> = <strong><em>localStorage</em></strong>.getItem(&#39;<em>Patience you must have, my young padawan</em>&#39;);</pre><pre><strong>console</strong>.log(<strong>yoda</strong>)</pre><p>And now when I check my console I have the <strong>value</strong> of patience .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*DRp4p-fWWklghJd49BpTsA.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3ohuAxV0DfcLTxVh6w%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3ohuAxV0DfcLTxVh6w%2Fsource.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3ohuAxV0DfcLTxVh6w%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="188" frameborder="0" scrolling="no"><a href="https://medium.com/media/75308d4ece8ec88477e0ce947ba342e8/href">https://medium.com/media/75308d4ece8ec88477e0ce947ba342e8/href</a></iframe><p>We need to <strong>name</strong> our keys <strong>wisely</strong> such that it doesn’t mean different things on the same website. <em>For example</em>, if I set my key as highscore , and if there are multiple games on my website, so at that point highscore will no longer reflect what it is supposed to reflect.</p><p><strong>Now what happens if I try setting an object as my value, but without it converting it into a string?</strong></p><p>Let’s try it out!</p><pre>let<strong><em> key </em></strong>=<strong><em> </em></strong>&#39;<strong>me</strong>&#39;;</pre><pre>let <strong>properties</strong> = {<br>&quot;<strong>friends</strong>&quot; : <strong>0</strong>,<br>&quot;<strong>life</strong>&quot; : <strong>false</strong>,<br>}</pre><pre><strong><em>localStorage</em></strong>.setItem(<strong>key</strong>, <strong>properties</strong>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*bg7uuwzHryQOQ2SwSZm4MA.png" /></figure><p>And if I try to retrieve it, i’ll only get a string &quot;[object Object]&quot; . So it really isn’t of much use here.</p><h3><strong>How do we solve this?</strong></h3><h4>JSON object</h4><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON"><strong>JSON object</strong></a> provides us with two methods: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse">parse()</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">stringify()</a>.</p><ul><li>parse() : will take a string and extract the arrays, the objects and other stuff alike from it.</li><li>stringify() : will take an object, array etc and convert it into a string.</li></ul><p>So if I try and <strong>stringify</strong> my properties object</p><pre>let <strong><em>myString</em></strong> = JSON.<strong>stringify</strong>(<strong>properties</strong>);</pre><pre><strong><em>localStorage</em></strong>.setItem(<strong>key</strong>, <strong>myString</strong>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*kvNjSFqv640KwPkXmgehSw.png" /></figure><p>Now, if I want to get the object back from the local storage, I’ll use the JSON method parse() .</p><pre>let <strong>propObject</strong> = JSON.<strong>parse</strong>(<strong>localStorage</strong>.getItem(<strong>key</strong>))</pre><pre><strong>console</strong>.log(<strong>propObject</strong>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*COCE3CvvWGg8zXt9cQqfmg.png" /><figcaption>Success (depression)!</figcaption></figure><h4><strong>Few more methods that could come handy</strong></h4><ul><li>clear() : <strong>erases everything</strong> in the local storage.</li><li>removeItem(key) : <strong>removes</strong> that <strong>particular key</strong>.</li><li>key(index) : <strong>returns</strong> the <strong>key</strong> at a particular <strong>index</strong>.</li></ul><h3>Now, let’s implement this in our last challenge to store our preferred theme!</h3><p>When the website loads for the <strong>first time</strong> on the <strong>browser</strong>, there is <strong>no key set </strong>for the preferred theme. We can just check if the <strong>key exists</strong> in the local storage by using <strong>getItem()</strong>, if it <strong>returns null</strong> then the <strong>key doesn’t exist</strong> else the key exists.<br>If you remember, we wanted the <strong>light theme to be our default theme</strong> and hence we had made lightThemeStatus true.</p><p>Let’s call our key lightTheme and initially set it to true in our local storage.</p><pre>if (<strong><em>localStorage</em></strong>.getItem(&quot;<strong>lightTheme</strong>&quot;) === <strong>null</strong>) {</pre><pre><strong>localStorage</strong>.setItem(&quot;<strong>lightTheme</strong>&quot;, &quot;<strong>true</strong>&quot;);</pre><pre>var <strong>lightThemeStatus</strong> = true;</pre><pre>}</pre><p>Once we’ve set the key in our <strong>local storage</strong>, we have to just initialised the lightThemeStatus variable to true, just like we had done previously.</p><h4>What if the key already exists?</h4><p>This is easy, we just use getItem() to get the value of the key lightTheme from the <strong>local storage</strong> and then <strong>parse</strong> it with the help of <strong>JSON object</strong>, so that the string value gets converted to the required boolean value we need.</p><p>Here is a breakdown of what I just said</p><pre>var <strong>lightThemeStatus</strong> = JSON.<strong>parse</strong>(<strong>localStorage</strong>.getItem(&quot;<strong>lightTheme</strong>&quot;));</pre><p><strong>localStorage</strong> — getItem() → JSON.parse() → <strong>lightThemeStatus</strong></p><h3>Setting theme when the website loads next time</h3><blockquote>If you recall, the way we were changing the theme was with the help of a <strong>button</strong> and whenever a <strong>click event</strong> occurred <strong>on that button</strong>, it would call a <strong>function</strong> to handle the event, and then that function would<strong> change the present theme</strong> of the website.</blockquote><p>We need to do a similar thing at the start of our script.</p><p>Like how we stored the <strong>current theme</strong> in a variable called currentTheme based on whether <strong>lightThemeStatus</strong> was true or false, <strong>similarly</strong>, we can declare a variable called <strong>onloadTheme</strong> which takes the <strong>previously active</strong> theme status from the <strong>local storage</strong> and then based on that store the required theme in the onloadTheme variable.</p><pre>let <strong>onloadTheme</strong> = <strong>lightThemeStatus</strong> ? <strong>lightTheme</strong> : <strong>darkTheme</strong>;</pre><pre>for (var <strong>i</strong> = 0; <strong>i</strong> &lt; Object.keys(<strong>onloadTheme</strong>).length; <strong>i</strong>++) {</pre><pre>document.documentElement.style.setProperty(</pre><pre>`--${Object.<strong>keys</strong>(<strong>onloadTheme</strong>)[<strong>i</strong>]}`,</pre><pre><strong>onloadTheme</strong>[Object.<strong>keys</strong>(<strong>onloadTheme</strong>)[i]]</pre><pre>);</pre><pre>}</pre><p>lightThemeStatus was set at the <strong>start</strong> when we checked whether the <strong>required key</strong> already existed in out <strong>local storage</strong> or not. We are just picking one property at a time from the onloadTheme object, and setting that <strong>key’s value to the style of our document</strong>.</p><p><strong>Checkout the previous challenge to understand in detail!</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FbGNwrMK%3Fheight%3D600%26slug-hash%3DbGNwrMK%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FbGNwrMK&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d4bccf0e0e999271af8f83b9a4b631a/href">https://medium.com/media/8d4bccf0e0e999271af8f83b9a4b631a/href</a></iframe><blockquote><strong>Here is a challenge for you</strong>: Try storing the states of the checkboxes in your local storage and then retrieving them whenever the page reloads.</blockquote><h4>Congratulation 🎉 ! You have just completed the fifth JavaScript challenge. I Hope your concept of storages in browser is clearer, and you’ll use them more often.</h4><p>All of the above-written code is available on <a href="https://github.com/reitwiec/12DaysOfJS"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50651ddf3fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/day-5-refresh-and-poof-gone-50651ddf3fc">Day 5— Refresh and poof, gone?</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 4— CSS Variables with JS!]]></title>
            <link>https://medium.com/iecse-hashtag/day-4-css-variables-with-js-f988d3c2e80e?source=rss-53b026960d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/f988d3c2e80e</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css-variables]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Reitwiec Shandilya]]></dc:creator>
            <pubDate>Tue, 17 Dec 2019 05:59:36 GMT</pubDate>
            <atom:updated>2019-12-17T06:02:27.251Z</atom:updated>
            <content:encoded><![CDATA[<h4>Adding themes with CSS variables</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZFWMTOx5gLu32NKJ-fPLcA.png" /></figure><h3>The 12 Days of JS?</h3><blockquote><strong>12 Days of JS</strong> is a series where we will tackle a new problem <em>every day</em> leading to Christmas, and solve it with the help of JavaScript ❤️. <strong>This isn’t a JavaScript 101 course</strong> but a way to improve the application of JavaScript in your projects! We aim to learn by application — encountering many new situations while talking about the hows, the whys and the whats we use to solve them.</blockquote><h3>Ever wondered how you can add themes to your website without adding so much extra CSS?</h3><blockquote>Well, with the introduction of <strong>CSS Variables</strong>, CSS has never been this powerful before.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3ofSB5PPO4cbZMK796%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3ofSB5PPO4cbZMK796%2Fsource.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3ofSB5PPO4cbZMK796%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="186" frameborder="0" scrolling="no"><a href="https://medium.com/media/581c81dd9fe8b686523dd51a4f489af6/href">https://medium.com/media/581c81dd9fe8b686523dd51a4f489af6/href</a></iframe><p><em>Before we start I just want to point out that I’m using some ES6 features like </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const"><em>const</em></a><em> and </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let"><em>let</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions"><em>arrow functions</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla"><em>etc.</em></a><em> If you are not familiar with those, check the provided links to learn more.</em></p><h3>Basic Setup</h3><p>Today, I’ll make use of the code that we had written in our <strong>Checkbox Challenge!</strong> and add a few more elements to it: a button to toggle between themes and maybe a <strong>logo</strong> which <em>changes with the theme</em>.</p><p>Since our main focus, today is on <strong>CSS variables</strong> and <strong>JavaScript</strong>, I’ve already made a boilerplate HTML file to work with today.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FWNbxzQR%3Fheight%3D600%26slug-hash%3DWNbxzQR%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FWNbxzQR&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/02e5967a7c29fa1562a1708ed60abba9/href">https://medium.com/media/02e5967a7c29fa1562a1708ed60abba9/href</a></iframe><h3>Setup our CSS variables</h3><p>The one thing that we need to know about CSS variables is that they have to be defined <strong>inside a selector</strong>. If you’ve used <strong>SASS</strong>, you know you can just define a variable anywhere and it doesn’t have to be inside a selector, which is not the case here.</p><p>The <strong>most often place</strong> where the <strong>custom properties</strong> are defined is the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:root">:root</a> . If you’ve never seen :root before, it’s basically going to the <strong>root</strong> element of your page which is your &lt;html&gt; element. The reason we put them in the :root and not in html is because it has a higher <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity">specificity</a> than html selector.</p><p>Another advantage of defining the variables in something like :root<br>is that they become <strong>global variables</strong>, which can be accessed by any element under it.</p><p>The usual format for defining a variable is</p><pre><strong>--variableName</strong> : value;</pre><p>If we define it inside our :root selector, it would look something like this</p><pre><strong>:root</strong> {</pre><pre><strong><em>--variableName</em></strong>: value;</pre><pre>}</pre><h4>Now we can go ahead and define our own variables!</h4><p>Let’s start off by defining the background colour of our document.</p><pre><strong>:root</strong> {</pre><pre><strong><em>--background</em></strong>: #fafafa;</pre><pre>}</pre><p>So we have defined a variable background that has the value #fafafa stored in it.</p><p>We can now use this variable in our usual selectors. The way variables are used in a regular property is with a little unusual syntax</p><pre><strong>CSSselector</strong> {</pre><pre><strong><em>property</em></strong>: <strong>var</strong>(<em>--variableName</em>);</pre><pre>}</pre><p>Here is how we can use the background variable that we have defined.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FMWYeGzg%3Fheight%3D600%26slug-hash%3DMWYeGzg%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FMWYeGzg&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecefef127286f9c24657a6c853a02d02/href">https://medium.com/media/ecefef127286f9c24657a6c853a02d02/href</a></iframe><blockquote>In a similar fashion, let’s define a few more variables. Make sure to define variables for all the properties you want to <strong>change with the theme</strong>.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FdyPXeEV%3Fheight%3D600%26slug-hash%3DdyPXeEV%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FdyPXeEV&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4482bfaa661dc4ba7c6d00a1150b4cc/href">https://medium.com/media/d4482bfaa661dc4ba7c6d00a1150b4cc/href</a></iframe><p>Let me explain the new variables that I have defined here.</p><ul><li>--navbarBackground: decides the background color of the <strong>navbar</strong>.</li><li>--buttonBackground: decides the background color of the <strong>theme toggle button</strong>.</li><li>--buttonText: decides the color of the text in the <strong>theme toggle button</strong>.</li><li>--content: decides the color of the text present in our <strong>list</strong>.</li><li>--inboxBackground: decides the background of our <strong>inbox</strong> element.</li><li>--inboxCrossed: decides the background color of our <strong>items when crossed/selected</strong>.</li><li>--logoUrl: decides the url from where we are fetching our <strong>logo</strong>.</li></ul><h3>Now that we have defined our CSS variables, let’s start adding JavaScript to it!</h3><p>Let us assume that the <strong>default theme</strong> of our website is <strong>light</strong>.</p><p>To keep track of which theme is <strong>currently active</strong>, let’s define a variable in such a way that it takes the <strong>default theme into consideration</strong>.</p><pre>let <strong><em>lightThemeStatus</em></strong> = <strong>true</strong>;</pre><p>lightThemeStatus tells us whether our website has light theme <strong>currently active or not</strong>. Since by default it is active, we have initialised it with the value true .</p><h3>New Definition of Dark Theme</h3><p>We need a way in which we can write a set of properties with values assigned to it.</p><p>A <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects"><strong>JavaScript object</strong></a> does a great work of handling key : value pairs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf33640f89696a8b61dc2ac59405d5e7/href">https://medium.com/media/bf33640f89696a8b61dc2ac59405d5e7/href</a></iframe><p>Here, our <strong>keys</strong> are our <strong>custom properties</strong> or the <strong>CSS variables</strong> that we had defined, and the <strong>values</strong> are the values that we want our custom properties to exhibit when it is in the <strong>darkTheme</strong>.</p><p>In a similar fashion, let’s also define an object to store the <strong>lightTheme</strong> properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7de3662cd9a8f5a2f32dad1d156771d6/href">https://medium.com/media/7de3662cd9a8f5a2f32dad1d156771d6/href</a></iframe><h3>Switch it</h3><p>If you’ve been following this series, you must be familiar with how one can get a <strong>reference</strong> to an HTML element. With the help of <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector">querySelector()</a> , we can get the reference of our <strong>toggle button</strong> and store it in some variable.</p><p>Let’s call that variable toggleButton .</p><pre>const <strong><em>toggleButton</em></strong> = <em>document</em>.<strong>querySelector</strong>(&quot;<strong><em>.switch-btn</em></strong>&quot;);</pre><p><strong>Our aim</strong> is it to switch the theme whenever the <strong>toggleButton</strong> is <strong>clicked</strong>.</p><p>With the help of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys"><strong>event listeners</strong></a>, we can add an <strong>event listener</strong> of type <strong>click</strong> to our toggleButton reference and then <strong>handle the event</strong> by calling some function.</p><p>Let’s call that function switchTheme() .</p><pre>function <strong>switchTheme</strong>() {</pre><pre>... do magic here</pre><pre>}</pre><pre><strong><em>toggleButton</em></strong>.addEventListener(&quot;<strong><em>click</em></strong>&quot;, <strong>switchTheme</strong>);</pre><p>So whenever a user clicks our toggle button, we call the function switchTheme().</p><h3>Do some magic</h3><p>As soon as our switchTheme() function is called we want to switch the value of lightThemeStatus variable to its negated value. When we are using <strong>light theme</strong> and we click the button, lightThemeStatus will change to false, and when we are using<strong> dark theme</strong> and we click the button, lightThemeStatus will become true.</p><pre><strong><em>lightThemeStatus</em></strong> = !<strong>lightThemeStatus</strong>;</pre><p>To get the <strong>properties of the current theme</strong>, we make use of lightThemeStatus .</p><pre>let <strong><em>currentTheme</em></strong> = <strong>lightThemeStatus</strong> ? <strong>lightTheme</strong> : <strong>darkTheme</strong>;</pre><p>Here, we have defined a variable called currentTheme which either takes the <strong>properties of the dark theme or the light theme</strong>. With the help of the <strong>ternary operator</strong>, we are returning the lightTheme <strong>object</strong> or the darkTheme <strong>object</strong> based on whether lightThemeStatus is <strong>true or false.</strong></p><p>Now, to make use of the properties of the current theme, we need to somehow access the keys of the currentTheme object.</p><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object"><strong>Object</strong></a><strong> </strong>constructor provides us with a method called <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys">Object.keys(objectName)</a> , which returns an <strong>array</strong> with all the keys of the specified object.</p><p>We can use this knowledge to access the <strong>keys individually</strong> by <strong>iterating</strong> over the <strong>array</strong> that is returned.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cb4933d6ef33e8493808c171202bbc9/href">https://medium.com/media/5cb4933d6ef33e8493808c171202bbc9/href</a></iframe><p>Object.keys(currentTheme).length gives us the length of the entire array. Then we are accessing each item with the help of its index.</p><p>Now that we are able to access the properties individually, we can start changing the CSS variables.</p><h4>How do we access the root element of our document?</h4><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement"><strong>Document.documentElement</strong></a><strong> </strong>returns the root element of our document.</p><p>With the help of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style">style</a> property provided by <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement">HTMLElement</a>, we can change the <strong>CSS of that element</strong>. style has a method called <a href="https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty">setProperty()</a> which allows us to set a <strong>value</strong> to the <strong>specified property</strong>.</p><pre><em>document.documentElement.style.</em><strong><em>setProperty</em></strong><em>(</em><strong><em>propertyName</em></strong>, <strong><em>value</em></strong><em>)</em></pre><p>At this point in time, let&#39;s have a look at all the things available to us</p><ul><li><strong>Individual properties</strong> to change.</li><li>Way to change a <strong>particular property</strong> of an <strong>HTML element</strong>.</li><li><strong>Values associated</strong> with the <strong>properties</strong> in our defined currentTheme object.</li></ul><p>With the knowledge of all of the above, we can write our code like this</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fembed%2Fpreview%2FvYEKaxY%3Fheight%3D600%26slug-hash%3DvYEKaxY%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Freitwiec%2Fpen%2FvYEKaxY&amp;image=https%3A%2F%2Fscreenshot.codepen.io%2F2967318.vYEKaxY.small.b139891b-ef6e-42cf-8e0d-bd0f3198d643.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d2e9198d9e01ff0541cd2a5ef0f85b9/href">https://medium.com/media/3d2e9198d9e01ff0541cd2a5ef0f85b9/href</a></iframe><p>We are now able to toggle between the themes!</p><h3>Things that can be improved</h3><ul><li>More addition of custom properties. We can add things like primaryColor , secondaryColor , fontFamilyUsed , the spacing between elements and a lot more.</li><li>Incorporating media-queries with CSS variables and JavaScript to make the responsiveness more flexible.</li><li>Since a lot of <a href="https://in.pcmag.com/gallery/131710/how-to-enable-dark-mode-on-your-web-browser">browsers</a> now have an option of dark mode preference, you can add your styling of the dark mode with the help of <a href="https://css-tricks.com/dark-modes-with-css/">media-queries</a>. But it restricts users from changing the website’s theme independent of the browser preference.</li></ul><p>There are a lot more things that can be improved and added. Let us know about your ideas in the responses below!</p><h4>Congratulation 🎉 ! You have just completed the fourth JavaScript challenge and can now add as many themes as you want to your website.</h4><p>All of the above-written code is available on <a href="https://github.com/reitwiec/12DaysOfJS"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f988d3c2e80e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/day-4-css-variables-with-js-f988d3c2e80e">Day 4— CSS Variables with JS!</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 3 — Make Your Own Video Player!]]></title>
            <link>https://medium.com/iecse-hashtag/day-3-make-your-own-video-player-9de1795ab1c3?source=rss-53b026960d34------2</link>
            <guid isPermaLink="false">https://medium.com/p/9de1795ab1c3</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[video-player]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Reitwiec Shandilya]]></dc:creator>
            <pubDate>Mon, 16 Dec 2019 05:58:22 GMT</pubDate>
            <atom:updated>2019-12-16T05:58:22.138Z</atom:updated>
            <content:encoded><![CDATA[<h3>Day 3 — Make Your Own Video Player!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JPRencWSXWnXIE3zAg-4w.png" /></figure><h3>The 12 Days of JS?</h3><blockquote><strong>12 Days of JS</strong> is a series where we will tackle a new problem <em>every day</em> leading to Christmas, and solve it with the help of JavaScript ❤️. <strong>This isn’t a JavaScript 101 course</strong> but a way to improve the application of JavaScript in your projects! We aim to learn by application — encountering many new situations while talking about the hows, the whys and the whats we use to solve them.</blockquote><h4>Ever wondered how websites like YouTube, Vimeo, Dailymotion and similar, make their video player? Today let’s make one of our own!</h4><p><em>Before we start I just want to point out that I’m using some ES6 features like </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const"><em>const</em></a><em> and </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let"><em>let</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions"><em>arrow functions</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla"><em>etc.</em></a><em> If you are not familiar with those, check the provided links to learn more.</em></p><h3>Basic project</h3><p>Let’s start by making an <strong>index.html</strong> file. First, we’ll design just a simple video player of our liking without any functionality, and then add JS to make it do cool stuff!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ca5d4e474d5075bfe42965a5982e1ac/href">https://medium.com/media/4ca5d4e474d5075bfe42965a5982e1ac/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3GSYu--JCJphw-g_awoXMQ.png" /><figcaption>Result of a simple video tag. We have hidden the default controls here.</figcaption></figure><p>If you right-click on the video, you’ll see an option for showing/hiding controls. Since our aim is to add our own <strong>custom controls</strong>, we’ll hide the <strong>default controls</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48b86c5d59407d92d0b8704ce971d6c3/href">https://medium.com/media/48b86c5d59407d92d0b8704ce971d6c3/href</a></iframe><p>Now, we add a <strong>play button</strong> which we will use to play and pause the video.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CstjJxvR2b770b38eKcu2A.png" /><figcaption>A simple button to play and pause.</figcaption></figure><p>Let’s make it more interesting by adding a <strong>volume slider</strong>, <strong>playback speed controller</strong>, and buttons to <strong>skip forward or backwards</strong> in time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebda516530df48ee7d2345b03e0a0be7/href">https://medium.com/media/ebda516530df48ee7d2345b03e0a0be7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*869ZiBDkKddhUSSeTTgHOw.png" /><figcaption>Basic skeleton of our video player</figcaption></figure><h4>Looks sad and dull?</h4><p>Let’s give it a little makeover with some <strong>CSS</strong>. 🎨</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Faugw261r%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Faugw261r%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F30ab0b469bfdf7eb4058b9992e0594bb%3Fs%3D80&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/8949586ad4e10f746652b1ffee1ca062/href">https://medium.com/media/8949586ad4e10f746652b1ffee1ca062/href</a></iframe><p>Now that our basic setup is ready, we can start adding JavaScript to our app!</p><h3>Selecting elements by CSS Selectors</h3><p>Let’s bring in our elements with the help of a method called <strong>querySelector()</strong>. It is similar to the method <strong>querySelectorAll()</strong>, that we used in one of our <strong>previous challenges</strong>; except that this returns only <strong>1 reference</strong> instead of all the available ones.</p><blockquote>If you missed that challenge, check it below!</blockquote><p><a href="https://medium.com/iecse-hashtag/day-1-the-checkbox-challenge-67d45bc09da2">Day 1 — The Checkbox Challenge!</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Fyxk9s0t2%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Fyxk9s0t2%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F30ab0b469bfdf7eb4058b9992e0594bb%3Fs%3D80&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6125a99d52fa804ad38775a1c4943a2/href">https://medium.com/media/f6125a99d52fa804ad38775a1c4943a2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C2red1OwwPthg5krOuRtHA.png" /></figure><h3>Pause. Play.</h3><p>As you can see, our video player doesn’t really do the most basic thing it is supposed to, <strong>play and pause the video</strong> So let’s make use of the toggle reference that we have available to us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*rjpkYU6ii-x9ISF9eM3_RQ.gif" /><figcaption>Checking out the properties of the video reference in the console</figcaption></figure><p>The video reference that we have, has a <strong>property</strong> that we can exploit to play or pause the video.</p><p><strong>video.paused</strong> : boolean</p><p>Now, we can use this property to <strong>toggle</strong> between play and pause.</p><p>Here is a breakdown of how we can use it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dea8fe493a0e94adf95fd8204c0de310/href">https://medium.com/media/dea8fe493a0e94adf95fd8204c0de310/href</a></iframe><p>It’s pretty straightforward, inside the function we are just checking if the <strong>video is paused or not</strong>, if it is <strong>paused then play</strong> the video, else pause the video.</p><p>Let’s write this function in a better, more efficient way!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Fwmypocav%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Fwmypocav%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F30ab0b469bfdf7eb4058b9992e0594bb%3Fs%3D80&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/43c84878a89e74f0b7089184a240577b/href">https://medium.com/media/43c84878a89e74f0b7089184a240577b/href</a></iframe><p>In this way, we are storing what the <strong>action</strong> should be performed, based on the <strong>status</strong> of the video. Then we are just accessing that property of the video.</p><h4>Now, how do we access this function?</h4><p>Let’s hook up the togglePlay() method to both when you click the <strong>video</strong> as well as when you click the <strong>play button</strong>.</p><p>To do this, we’ll simply add an <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventListener"><strong>event listener</strong></a> of type <strong>click</strong> to both the elements.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Fd6ugh9c8%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Fd6ugh9c8%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F30ab0b469bfdf7eb4058b9992e0594bb%3Fs%3D80&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/81c8a4d3f4a395f2320a5c8f0cbeff42/href">https://medium.com/media/81c8a4d3f4a395f2320a5c8f0cbeff42/href</a></iframe><h3>Did you notice a bug?</h3><p>As you can see, the <strong><em>play button</em></strong> symbol isn’t changing on playing or pausing. Before we solve that, we need to remember that there <strong>aren’t</strong> <strong>just two ways</strong> of playing or pausing. A user can probably make use of some <strong>extension</strong> that does the toggling or maybe just <strong>directly call</strong> the <em>play property</em> in the <strong>console</strong>. So in order to make sure that <em>irrespective </em>of <strong>how</strong> the video is paused or played, we need to change the symbol.</p><h4>Pause yourself for a minute, and try to figure out a good solution.</h4><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement">HTMLMediaElement</a> provides us with two events that we can use for our purpose: <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play_event">play</a> event and <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause_event">pause</a> event.</p><ul><li>play: fires whenever the paused property is changed from true to false .</li><li>pause: fires when a request to pause an activity is made and the activity has entered its paused state.</li></ul><p>So whenever the video is in either of those two states, we want to call our event handler callback function to change the symbol.</p><p>Let’s call our event handler method updateSymbol().</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Fdgbpwnrf%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Fdgbpwnrf%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F30ab0b469bfdf7eb4058b9992e0594bb%3Fs%3D80&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bf257e7a6ecacaac385982b162a131e/href">https://medium.com/media/6bf257e7a6ecacaac385982b162a131e/href</a></iframe><p>Whenever we pause/play the video, the reference is passed to our updateSymbol method. Now, this allows us to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this"><strong>this</strong></a><strong> </strong>which is a reference to the <strong>video</strong>, and then we can use its paused property to set the state of our symbol.</p><h3>Let’s skip ahead!</h3><p>If we go back to where we’ve defined our skip buttons, you’ll notice they have an attribute of data-skip and our skipButtons variable is equal to anything that has data-skip attribute.</p><p>The <a href="https://www.w3schools.com/tags/att_data-.asp">data</a> attribute allows us to store custom data private to the page. Like here, we have made a data attribute called skip, in which we have stored the <strong>amount of skip in time </strong>we want the button to make.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec06ad8a05d06db30ac2e3660d2bd87a/href">https://medium.com/media/ec06ad8a05d06db30ac2e3660d2bd87a/href</a></iframe><p>The <strong>negative value</strong> means, we want to <strong>turn back time</strong> (<em>to the good old day</em>s) and the <strong>positive value </strong>means we want to go <strong>ahead in time</strong>.</p><h4>How do we access the attribute value?</h4><p>We can use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset"><strong>dataset</strong></a> property associated with the HTML element, to access the <strong>skip</strong> value.</p><p>Now it’s really simple, we just need to add an <strong>event listener</strong> of type <strong>click</strong> to skipButtons and then call a function to handle the event. Let’s call that function ourSkippingFunction().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a2208c40c5e04d5c2e4795e401ba963/href">https://medium.com/media/6a2208c40c5e04d5c2e4795e401ba963/href</a></iframe><p>So, whenever we <strong>click our skipping buttons</strong>, we call the ourSkippingFunction() which will the take the value of <strong>skip</strong> from the <strong>dataset</strong> property and then we can use it to manipulate the video properties.</p><blockquote>Now, the way we can skip forward or backward, is by using <strong><em>.currentTime</em></strong> property of the <em>video</em> reference. <em>.currentTime</em> provides us with the <strong>current time</strong> of the video playback.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2F5oz3hu46%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2F5oz3hu46%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F30ab0b469bfdf7eb4058b9992e0594bb%3Fs%3D80&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba18367a76af38d7e6dc82b6cff07db1/href">https://medium.com/media/ba18367a76af38d7e6dc82b6cff07db1/href</a></iframe><p>Here, what is being done is, once the function is called, we are storing the <strong>skip</strong> value in a variable called skip . Since dataset.skip returns a string, we need to parse it into a float value. Then we are just changing the current time of the video by adding the skip value to it.</p><h3>Faster and louder 🚨</h3><p>We can now work on controlling the <strong>volume</strong> and the <strong>playback rate</strong>.</p><p>The ranges variable that we had created, has both the ranges available in it.</p><p>So we can add some sort of <strong>event listener</strong> to it and somehow control it.</p><p>Now, <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement">HTMLElement</a> provides us with an event called change .</p><ul><li>change - fires for <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input">&lt;input&gt;</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select">&lt;select&gt;</a>, and <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea">&lt;textarea&gt;</a> elements when there is a change in the element&#39;s value.</li></ul><p>To handle the event, let’s make a method called rangeUpdate()</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf0cf996a0efa33e18dd0dd450f82333/href">https://medium.com/media/cf0cf996a0efa33e18dd0dd450f82333/href</a></iframe><p>Our input element that we had created earlier for the ranges, has an <strong>attribute</strong> called <a href="https://www.w3schools.com/tags/att_input_name.asp">name</a>. Now coincidentally, the names that we have defined are <strong>actual properties of the video</strong>. 🤯</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Fvsbfkpyt%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Fvsbfkpyt%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F30ab0b469bfdf7eb4058b9992e0594bb%3Fs%3D80&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/54db54a9976b4c9908d2d8880903f7f9/href">https://medium.com/media/54db54a9976b4c9908d2d8880903f7f9/href</a></iframe><p>So here we are again making use of this, and here it is referencing either to the volume range or the playbackRate range. this.name will either return &quot;volume&quot; or &quot;playbackRate&quot; , which we can use to access the property of video and then set that property’s value to this.value i.e., which is the current value of the range.</p><blockquote><strong>Extra </strong>: If you notice, the changes in the ranges are visible only <strong>once you leave</strong> the mouse at the <strong>new position</strong>. To do a <strong>real-time</strong> change, just change the event listener to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event"><strong><em>mousemove</em></strong></a><strong> </strong>and voila!</blockquote><h3>Now we’re left with only two things</h3><ul><li>Updating the progress bar in real-time</li><li>As you move the progress bar, the video should adjust to the corresponding place</li></ul><p>Since our progress bar has display:flex property applied to it, we can take the help of <a href="https://www.w3schools.com/cssref/css3_pr_flex-basis.asp">flex-basis</a>, which specifies the length of our flexible item, to change the width of our progress bar.</p><p>Here, we <strong>don’t know</strong> what the <strong>length</strong> should be in <strong>pixels</strong>, but, we can calculate the <strong>percentage of the video that is completed</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4tcvdfRVFJ9w4Bb5hFvXCw.gif" /><figcaption>Here I am changing the value of flex-basis to adjust the width of the progress bar</figcaption></figure><h4>How will we calculate the percentage of the video completed?</h4><p>We can simply just make use of the properties video.currentTime and video.duration , which will give us the <strong>current time</strong> and the <strong>duration</strong> of the video. And then with the help of some elementary math we can calculate the percentage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a46961463c46c43d17402f52dfb4820/href">https://medium.com/media/5a46961463c46c43d17402f52dfb4820/href</a></iframe><p>Now that we have the percentage, we can change the <strong>style</strong> of our progress bar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58b3f0dc92e76fd9c1ea50bfa0eaab66/href">https://medium.com/media/58b3f0dc92e76fd9c1ea50bfa0eaab66/href</a></iframe><h3>But wait… When do we exactly do the above calculations and how do we do it in real-time?</h3><p>You guessed it right! we’ll again make use of an <strong>event listener</strong>, but which one?</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement">HTMLMediaElement</a> provides us with an event called <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/timeupdate_event">timeupdate</a> .</p><ul><li>timeupdate - fires whenever the time indicated by currentTime attribute of the element, in our case the video, is updated.</li></ul><p>To handle this change in time, let’s define a method called handleProgress() .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5fa0e295088448316ecc0fd78f3c0fa/href">https://medium.com/media/d5fa0e295088448316ecc0fd78f3c0fa/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Fm5byn8xa%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Fm5byn8xa%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F30ab0b469bfdf7eb4058b9992e0594bb%3Fs%3D80&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/dabaa442305ff57b3b37ebd0a3a7e432/href">https://medium.com/media/dabaa442305ff57b3b37ebd0a3a7e432/href</a></iframe><h3>Let’s see how we can make the scrubbing of the progress bar</h3><p>We need to somehow <strong>change</strong> the <strong>video timecode</strong> to the place <strong>where we click</strong> on the progress bar.</p><p>Since we are talking about <em>clicking</em> on the progress bar, let’s add an event listener of type <strong>click</strong>, and to handle the even let’s define a function say scrub().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d808a92e7b5da133c6774980bf0473c/href">https://medium.com/media/1d808a92e7b5da133c6774980bf0473c/href</a></iframe><p>Let’s have a look at the event that is handled by the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*wkUESGjeqzNbo4MEx2fNgw.png" /><figcaption>Console log of the event</figcaption></figure><p>Our event has two interesting properties that we might be able to make use of: offsetX and offsetY. But, since the scrubbing only takes place in the <strong>X-direction</strong>, we can ignore offsetY .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*FmjouAn8nDRYunC2310pfQ.png" /><figcaption>317px into the progress bar</figcaption></figure><p>offsetX property basically tells us how far <strong>into</strong> the <strong>progress bar </strong>we are from the <strong>start</strong>.</p><p>Given that knowledge, we can do a little bit of math to find our <strong>new position</strong> on the <strong>timeline</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/697c5e6a4ff45334e4eeaddce3b195b0/href">https://medium.com/media/697c5e6a4ff45334e4eeaddce3b195b0/href</a></iframe><p>progress.offsetWidth allows us to grab the <strong>width</strong> of the entire <strong>progress bar</strong>.</p><p>Now, that we have the scrub time, we can just update the <strong>current time</strong> of the video and we’re done!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2F9edvgzoq%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2F9edvgzoq%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F30ab0b469bfdf7eb4058b9992e0594bb%3Fs%3D80&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f1c24e14ec231d0435a85e7d73824d8/href">https://medium.com/media/4f1c24e14ec231d0435a85e7d73824d8/href</a></iframe><blockquote><strong>On your own:</strong> Try implementing a method by which you can change the video timecode while you <strong>drag on the progress bar</strong>. (<strong>HINT:</strong> Try using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event"><em>mousemove</em></a> event listener)</blockquote><h3>EXTRA EXTRA EXTRA ! !</h3><p>Our video player is ready, but there is one more thing we can add to it!</p><h4>F U L L S C R E E N</h4><p>To do this, let’s add a button to our player that’ll help us switching between screens.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4beaef42fa8ac519dd15385f27e3f3f1/href">https://medium.com/media/4beaef42fa8ac519dd15385f27e3f3f1/href</a></iframe><p>With the help of <strong>querySelector()</strong> we can get the reference to that button and store it in a variable called fullscreenBtn .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85385b915c799059c288f36c9efe09a3/href">https://medium.com/media/85385b915c799059c288f36c9efe09a3/href</a></iframe><p>Now, whenever the user <strong>clicks</strong> on the fullscreen button we need to make our video fullscreen.</p><p>Our player reference has a method called <a href="https://www.w3schools.com/jsref/met_element_requestfullscreen.asp">requestFullscreen()</a>, which allows us to open it in full-screen.</p><p>So, we just need to add an<strong> event listener </strong>of type <strong>click</strong> to fullscreenBtn, and then just call that function!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db8a4598d0eba902fc1dfec17c0cee37/href">https://medium.com/media/db8a4598d0eba902fc1dfec17c0cee37/href</a></iframe><h3>Check out the final application below!</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Fkxey8r3o%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2Freitwiec%2Fkxey8r3o%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F30ab0b469bfdf7eb4058b9992e0594bb%3Fs%3D80&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/f292376626c24b9962aad9e3003d04d6/href">https://medium.com/media/f292376626c24b9962aad9e3003d04d6/href</a></iframe><h4>Congratulation 🎉 ! You have just successfully made your own custom video player.</h4><p>All of the above-written code is available on <a href="https://github.com/reitwiec/12DaysOfJS"><strong>Github</strong></a><strong>. </strong>Watch this space for more interesting challenges, up next in this series!</p><p>Confused about something? Let us know in the responses below. 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9de1795ab1c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/iecse-hashtag/day-3-make-your-own-video-player-9de1795ab1c3">Day 3 — Make Your Own Video Player!</a> was originally published in <a href="https://medium.com/iecse-hashtag">Hashtag by IECSE</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>