<?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 Maxim Maeder on Medium]]></title>
        <description><![CDATA[Stories by Maxim Maeder on Medium]]></description>
        <link>https://medium.com/@maximmaeder?source=rss-1cd9eb3a0189------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yiBBWXL-LDRPBBfBwFI5Pg.png</url>
            <title>Stories by Maxim Maeder on Medium</title>
            <link>https://medium.com/@maximmaeder?source=rss-1cd9eb3a0189------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 01:17:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maximmaeder/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[Line Chart with Svelte]]></title>
            <link>https://medium.com/@maximmaeder/line-chart-with-svelte-1fa32ee05379?source=rss-1cd9eb3a0189------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fa32ee05379</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[sveltekit]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Maxim Maeder]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 12:59:15 GMT</pubDate>
            <atom:updated>2023-06-10T19:51:44.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*t29WSuazSXcnKRBV.png" /></figure><p>In this Tutorial, we will create a Line Chart Svelte Component, which we can use in our Svelte Applications. We will use Scalable Vector Graphics (SVG) which are HTML. With SVG’s help, we can create a Line Chart with a few lines of code. We will also use Svelte’s reactive variables to make the Line Chart interactive.</p><p>We’ll also style it with CSS / SCSS. Below you will see what we will create today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cwwdBIOWGCdSpqjd.png" /></figure><p>Within the Component, we’ll distribute the given data into a range to fit into the Diagram; this Behavior may be nothing for you, so your main takeaway could be how incredible SVG is and how easy it is to create Graphics with it.</p><p>First, we will create the Line Chart Component. Then we will use it in a Svelte Application.</p><p>Let’s get started.</p><h3>Line Chart Component</h3><p>The Component consists of a script tag, a div container with an SVG, and a style tag.</p><h3>Script of the Line Chart Component</h3><p>Within our line-diagram.svelte file, we start by exporting a name and values property. The name property will be used as the title of the Diagram, and the values property will be used to draw the Diagram. The values property is an array of numbers.</p><p>Next up, we define the Diagram’s height, width, and vertical padding; these numbers are mainly arbitrarily chosen to fit the Diagram. Because later down the line, we will fit all the data within this range.</p><p>Furthermore, we will get the highest and lowest value of the dataset, and calculate the proportions between our desired range and the range of the data. This will be used to scale the data to fit the Diagram.</p><p>This all sounds rather complicated, but bear with me here.</p><pre>&lt;script lang=&quot;ts&quot;&gt; export let name : string = &#39;&#39; export let values : number[] // These values are arbitrarily chosen to fit the Diagram let height = 50; let width = 100; let padding = 5; $: highestValue = values.reduce((a, b) =&gt; Math.max(a, b)) $: lowestValue = values.reduce((a, b) =&gt; Math.min(a, b)) $: multiplier = ( height - 2 * padding ) / (highestValue - lowestValue); ... &lt;/script&gt;</pre><p>Lastly, within the script tag, we’ll define a reactive variable, path which will be used to draw the Diagram. Then we use a reactive block to calculate the path. The path is a string containing the <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths">SVG Path commands</a> to draw the Diagram.</p><pre>let path = &#39;&#39; $: { path = &quot;M0 &quot; + (height); for (let i = 0; i &lt; values.length; i++) { let yValue = height - (((values[i] - lowestValue) * multiplier) + padding) ; let xValue = i / (values.length - 1) * width; path += &quot; L &quot; + xValue + &quot; &quot; + yValue; } path += &quot; L&quot; + width + &quot; &quot; + height; path += &quot; L 0 &quot; + height; path += &quot; Z&quot;; }</pre><h3>HTML of the Line Chart Component</h3><p>Next, we will create the HTML for our Component, consisting of a div container with an SVG. The SVG has a viewBox which defines the size of the SVG. The viewBox is a string that contains the x and y position of the top left corner and the width and height of the SVG. We will use the width and height variables we defined earlier.</p><p>We also set the preserveAspectRatio attribute to none so the SVG will scale to fit the container.</p><pre>&lt;div class=&quot;container&quot;&gt; &lt;svg class=&quot;diagramm_svg&quot; viewBox={&quot;0 0 &quot; + width + &quot; &quot; + height} preserveAspectRatio=&quot;none&quot; &gt; &lt;!-- More to Come --&gt; &lt;/svg&gt; &lt;/div&gt;</pre><p>We start by defining a tag within the SVG. The defs tag is used to define SVG Elements, which can be reused within the SVG. In our case, we will define a linear gradient which we will use to fill the line of the Diagram.</p><p>After that, we create this line with a path element. The path is defined by the path variable we defined earlier. This path element uses the gradient by referencing it by its id in the fill attribute.</p><p>Lastly, we add text labels to our Diagram. Mind the text-anchor and dominant-baseline attributes.</p><pre>&lt;!-- Show Labels --&gt; &lt;text x={width - 2.5} y={height - padding} class=&quot;label_text&quot; text-anchor=&quot;end&quot; dominant-baseline=&quot;middle&quot;&gt;{ Math.round(lowestValue) }&lt;/text&gt; &lt;line x1={width - 2} y1={height - padding} x2={width} y2={height - padding} class=&quot;label_line&quot;&gt;&lt;/line&gt; &lt;text x={width - 2.5} y={padding} class=&quot;label_text&quot; text-anchor=&quot;end&quot; dominant-baseline=&quot;middle&quot;&gt;{ Math.round(highestValue) }&lt;/text&gt; &lt;line x1={width - 2} y1={padding} x2={width} y2={padding} class=&quot;label_line&quot;&gt;&lt;/line&gt; &lt;text x=&quot;2&quot; y={padding} class=&quot;title_text&quot;&gt;{ name }&lt;/text&gt;</pre><h3>CSS of the Line Chart Component</h3><p>Lastly, we add some CSS to our Component. We will use SCSS for this. We start by defining the container and the SVG. We also add a border to the SVG so we can see the size of it. I won’t go over it, but you see the code below.</p><pre>.container { background-color: hsl(200 50% 20%); background: linear-gradient(150deg, hsl(200 50% 20%), hsl(200 50% 10%)); height: 100%; display: flex; flex-direction: column; justify-content: center; .diagramm_svg { width: 100%; height: 100%; .label_line { stroke-width: 0.3px; stroke: hsl(200 0% 100% / 0.3); } .title_text { font-size: 3px; fill: white; font-weight: 600; } .label_text { font-size: 2px; fill: white; text-align: right; } } }</pre><h3>Using the Line Chart Component</h3><p>Now how do we use this Component? To demonstrate this, I will use the Weather API that I have used in <a href="https://maximmaeder.com/weather-app-with-html-sass-and-javascript/">this article</a> to make a simple diagram.</p><p>We start by fetching the API URL and getting the json for it. We can then put this data into the weatherDataPromise variable.</p><pre>async function getWeatherData() { const response = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=52.52&amp;longitude=13.41&amp;hourly=temperature_2m`) return await response.json() } let weatherDataPromise = getWeatherData()</pre><p>Lastly, we use the svelte await block to wait for the promise to resolve. We then pass the data to our LineDiagram Component.</p><pre>&lt;div class=&quot;container&quot;&gt; &lt;h2&gt;My Cool Line Diagram&lt;/h2&gt; &lt;br&gt; &lt;div class=&quot;weather_container&quot;&gt; &lt;!-- Await --&gt; {#await weatherDataPromise} &lt;p&gt;Waiting for weather data...&lt;/p&gt; {:then data} &lt;LineDiagram values={data.hourly.temperature_2m} name=&quot;Weather Data&quot;/&gt; {:catch error} &lt;p style=&quot;color: red&quot;&gt;{error.message}&lt;/p&gt; {/await} &lt;/div&gt; &lt;/div&gt;</pre><h3>Conclusion</h3><p>That’s it; I hope you had a good time reading and that you learned something new. As you see, SVG is mighty when used correctly and dynamically. You can, for example, make a <a href="https://www.reddit.com/r/ProgrammerHumor/comments/13zn0k1/responsive_dog/?utm_source=share&amp;utm_medium=web2x&amp;context=3">Responsive Dog</a>.</p><p><em>Originally published at </em><a href="https://maximmaeder.com/line-chart-with-svelte/"><em>https://maximmaeder.com</em></a><em> on June 4, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fa32ee05379" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Svelte Store to manage the color theme]]></title>
            <link>https://medium.com/@maximmaeder/custom-svelte-store-to-manage-the-color-theme-b925cf52ecc0?source=rss-1cd9eb3a0189------2</link>
            <guid isPermaLink="false">https://medium.com/p/b925cf52ecc0</guid>
            <category><![CDATA[sveltejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[user-interface]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[svelte]]></category>
            <dc:creator><![CDATA[Maxim Maeder]]></dc:creator>
            <pubDate>Wed, 19 Apr 2023 09:06:19 GMT</pubDate>
            <atom:updated>2023-04-21T05:35:22.985Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to this relatively short and simple tutorial on creating a <a href="https://svelte.dev/tutorial/custom-stores">Custom Svelte Store</a> that manages the current color scheme.</p><p>We will make it so the default color scheme from the Operating System is used, and then the Preferences are stored in Local Storage.</p><p>It will also register theme changes in other tabs, windows, and iframes. To do this, we will learn about the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API">Broadcast API</a>.</p><p>Lastly, we learn how to use our custom store in our application with Tailwindcss.</p><p>To start, we create a new <a href="https://vitejs.dev/">Vite</a> project with the following command.</p><pre>npm create vite@latest</pre><p>You can now answer all the questions. Regarding the framework, you chose Svelte, and it does not matter if you only use Svelte or Svelte Kit because the feature we build here will work in both.</p><p>You can then run the project by typing npm run dev, assuming you are in your project folder where the package.json file lies.</p><h3>Creating a Custom Svelte Store</h3><p>How do we make a custom store? In Svelte regular stores are created with the readable/writable, but these functions actually just return objects with three properties: subscribe, set, and update.</p><p>We can create our own store by using the subscribe method of a regular store and return our own object.</p><p>The subscribe method/property is mandatory, but we can define other functions called whatever we want that can be called on the store object.</p><p>So let’s start by creating a new file called store.js and import the writable function from Svelte.</p><pre>import { writable } from &quot;svelte/store&quot;;</pre><h3>OS Default</h3><p>We then continue by getting the OS default color scheme. In CSS we can apply styles conditionally based on the current color scheme with the prefers-color-scheme media query. And we can use the matchMedia function in js to find out if the media query is true or not.</p><pre>// Get the OS default color scheme<br>const media_query = matchMedia(&quot;(prefers-color-scheme: dark)&quot;)<br>const os_default = media_query.matches ? &quot;dark&quot; : &quot;light&quot;;</pre><p><em>We could also add an event listener to the media query to listen for changes. but we won’t utilize this feature here.</em></p><h3>Base Store</h3><p>Next, we call the writable method with either the OS default or the value from local storage if defined.</p><p>We destructure the subscribe and update methods from the returned object.</p><pre>// Get the current color scheme from local storage, or default to light<br>const { subscribe, update } = writable(localStorage.getItem(&quot;colorScheme&quot;) ?? os_default);</pre><h3>Broadcast Channel</h3><p>Continuing, we create a new Broadcast Channel, a way to communicate between tabs, windows, and iframes. It’s important to note that the channel name must be the same in all the places we want to communicate. But in this example, it’s alright because we only have one channel.</p><pre>// Create a channel so we can communicate with other tabs/windows/iframes<br>const channel = new BroadcastChannel(&quot;colorScheme&quot;);<br><br>// Listen for messages from other tabs/windows/iframes<br>channel.addEventListener(&quot;message&quot;, event =&gt; {<br>    update(() =&gt; event.data);<br>});</pre><p>We can add an event listener to this channel for messages from other tabs, windows, and iframes. When we receive a message, we update the store with the new value, which will be light or dark.</p><h3>Toggle Function</h3><p>After that, we define a function that will be added to the store to toggle the current color scheme. This function will be the only way to change the color scheme.</p><p>For function, we use update, a method of the writable store. It takes a function as an argument, and this function will be called with the current value of the store. We can then return a new value, which will be the new value of the store.</p><pre>const toggle = () =&gt; update(n =&gt; {<br>    const newColorScheme = n === &quot;light&quot; ? &quot;dark&quot; : &quot;light&quot;<br><br>    // Save the new color scheme to local storage<br>    localStorage.setItem(&quot;colorScheme&quot;, newColorScheme);<br><br>    // Send the new color scheme to other tabs/windows/iframes<br>    channel.postMessage(newColorScheme);<br><br>    return newColorScheme;<br>});</pre><p>We also set the value in the local storage and, we post a message on the channel with the new color scheme.</p><p>Below you see where to view values in the local storage with the dev tools in MS Edge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fk6CiNzxx8CKpP47.gif" /></figure><h3>Exporting the Store</h3><p>Lastly, we export the store object with the subscribe and toggle methods.</p><pre>// A store object must return a subscribe function, all other properties are optional.<br>export const colorScheme = { subscribe, toggle };</pre><h3>Using the Custom Svelte Store</h3><p>Now we have a custom store that we can use in our application. We can import the store in our components like this.</p><pre>&lt;script&gt;<br>    import { colorScheme } from &quot;./store&quot;;<br>&lt;/script&gt;</pre><h3>Handling Color Scheme in the styling</h3><p>To handle our color theme store, we could set a class on the root element and use the <a href="https://tailwindcss.com/docs/dark-mode#toggling-dark-mode-manually">class strategy</a> in Tailwindcss.</p><pre>&lt;script&gt;<br>    import { colorScheme } from &quot;./store&quot;;<br>    <br>    // Set the color scheme each time it changes.<br>    // Doing it this way could be useful if you use Tailwind with the class strategy.<br>    $: {<br>        document.firstElementChild.setAttribute(&quot;class&quot;, $colorScheme);<br>        document.firstElementChild.style.colorScheme = $colorScheme;<br>    };<br>&lt;/script&gt;</pre><h3>Toggle Button</h3><p>Lastly, to toggle the color scheme, we can add a button that calls the toggle function on the store.</p><pre>&lt;button on:click={() =&gt; colorScheme.toggle()}&gt;Toggle&lt;/button&gt;</pre><h3>Conclusion</h3><p>Thats it! We now have a custom store that we can use to toggle the color scheme in our application. This store will even register changes on other tabs, windows, and iframes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b925cf52ecc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conway’s Game of Life with JavaScript — Maxim Maeder]]></title>
            <link>https://medium.com/@maximmaeder/conways-game-of-life-with-javascript-maxim-maeder-147d7fe3ac87?source=rss-1cd9eb3a0189------2</link>
            <guid isPermaLink="false">https://medium.com/p/147d7fe3ac87</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[conways-game-of-life]]></category>
            <category><![CDATA[games]]></category>
            <dc:creator><![CDATA[Maxim Maeder]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 18:19:13 GMT</pubDate>
            <atom:updated>2023-04-21T11:09:24.151Z</atom:updated>
            <content:encoded><![CDATA[<h3>Conway’s Game of Life with JavaScript — Maxim Maeder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*s167CCae6r8pWwV7.png" /></figure><p>In this Tutorial we will implement Conway’s Game of Life as an interactive website using JavaScript, HTML and CSS. If you don’t know what the game of life is you can read about it on <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">wikipedia</a>. In a nutshell, Conway’s Game of Life is a Zero Player game where the player can set the state of tiles in a 2D grid plane to either dead or alive and then start a simulation. Every tick/frame of each tiles survival or state will be set according to its neighbors, if it has 2 or less alive neighbors, it will die of loneliness. If it has four or more it will die of overpopulation, lastly tiles will stay alive or even be born if they have three or two alive neighbors.</p><p>below you see some examples on wikipedia of special formations that can be created with the rules of the game of life. There are even some crazy things like glider guns that create infinite gliders.</p><p><strong>Block</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/99/0*XFjQfaqnHEFDXQFR.png" /></figure><p><strong>Blinker</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/82/0*GxmNEWs2-QP3Uot7.gif" /></figure><p><strong>Glider</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/84/0*qpA_CBQFKvxFxh7j.gif" /></figure><p>You can also visit the website we create today <a href="https://demos.maximmaeder.com/demo/conway/">here</a>. So let’s get started.</p><h3>Markup for the User Interface</h3><p>Before we get into the difficult JavaScript of this program lets cover the HTML for this website. Keep in mind that I wont go over everything, I will simply explain the important bits.</p><p>In the head of our page we add the link to the CSS file and we also link to the JavaScript via a script tag that has the defer attribute that will make it so the script is executed after the HTML content has been parsed.</p><p>Continuing we add two div&#39;s to the page: The first one holds the controls for the Website which mainly consists of buttons for running, stopping and resetting the simulation. We add Id&#39;s to all of these so we can get them easily later in the JS code. The second one holds the actual grid and we give it the class playground.</p><pre>&lt;div class=&quot;controls&quot;&gt; &lt;div&gt; &lt;button id=&quot;run&quot;&gt;Run&lt;/button&gt; &lt;button id=&quot;stop&quot;&gt;Stop&lt;/button&gt; &lt;button id=&quot;reset&quot;&gt;Reset&lt;/button&gt; &lt;input type=&quot;text&quot; placeholder=&quot;FrameTime (250ms)&quot; id=&quot;frametime&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;playground&quot;&gt;&lt;/div&gt;</pre><h3>JavaScript for the Game of Life</h3><p>Lets continue with the JavaScript for the Game of Life.</p><p>We simply start by defining a bunch of variables that will come in handy later. Some of them are needed to keep track of the state of the programme like isRunning.</p><pre>const playground = document.querySelector(&#39;.playground&#39;); const runButton = document.querySelector(&#39;#run&#39;) const stopButton = document.querySelector(&#39;#stop&#39;) const resetButton = document.querySelector(&#39;#reset&#39;) const frametimeInput = document.querySelector(&#39;#frametime&#39;) const controlsContainer = document.querySelector(&#39;.controls&#39;) let isRunning = false; let intervalId; const rows = 50 const columns = 70 let gridData = [] let savedData;</pre><p>After that we populate the gridData array with objects each representing a cell in our grid. For each cell we store row, column and live. Then we also set the grid-template-columns CSS property on the playground cell container so it will show the the cell positioned correctly.</p><pre>for (let row = 0; row &lt; rows; row++) { for (let column = 0; column &lt; columns; column++) { gridData.push({ row: row, column: column, live: false, }) } } playground.style.gridTemplateColumns = `repeat(${columns}, var(--size))`</pre><h3>renderCells Function</h3><p>Continuing we call the renderCells function that will as its name implies rerender all the reflecting their state according to the gridData Array. This function will be used often so lets go over it right now.</p><pre>renderCells(gridData)</pre><p>The function starts by emptying the playground cell container via its innerHTML property. We then loop over the gridData Array and create a new div for each one. Depending on its live property we add a class with the same name. In case the simulation is not running we also add an event listener to this div. This listener enables the user to toggle the live property of the given cell.</p><pre>function renderCells() { playground.innerHTML = &#39;&#39; gridData.forEach(cellData =&gt; { const cellNode = document.createElement(&#39;div&#39;) cellNode.classList.add(&#39;cell&#39;) cellNode.classList.toggle(&#39;live&#39;, cellData.live) playground.appendChild(cellNode) if ( isRunning ) return cellNode.addEventListener(&#39;pointerdown&#39;, () =&gt; { cellData.live = !cellData.live; renderCells() }) }); }</pre><h3>Simulating the Game Of Life</h3><p>Now lets get to the center of this whole programme. For this we add an event listener to the run button. It will set the isRunning variable to true so the user cant interact with the grid and we add the is_running class to the controls so we can apply some styling to them when the simulation is running. Now comes something important; In the Game of Life each tiles state is determined at the same time, so we have to keep that in mind in our code. Later we will cover the simulateGeneration function that does what is says. In JavaScript objects are passed by references and the only way to get fully rid of any and all connection we have to serialize the object and deserialize it with JSON.</p><pre>runButton.addEventListener(&#39;pointerdown&#39;, () =&gt; { isRunning = true; controlsContainer.classList.add(&#39;is_running&#39;) savedData = JSON.stringify(gridData) const simulateGeneration = () =&gt; { ... } simulateGeneration() const time = parseInt(frametimeInput.value) || 250 intervalId = setInterval(simulateGeneration, time) })</pre><p>We then also run a setInterval with our function and we save its returned Id for later so we can also finish it.</p><p>Now let’s go over the function that simulates a generation. Inside this function we need to use the JSON serialization trick to make an exact copy of the gridData variable. We then loop over each cell and find all its neighbors. Depending on that we set the state of this cell.</p><pre>const copiedGridData = JSON.parse(JSON.stringify(gridData)) /* Make a copy so the state is the same for all cells */ copiedGridData.forEach((copiedCell, index) =&gt; { cell = gridData.find(o =&gt; o.row == copiedCell.row &amp;&amp; o.column == copiedCell.column) const adjacentCells = [ /* Top and Bottom */ copiedGridData.find(o =&gt; o.row == cell.row + 1 &amp;&amp; o.column == cell.column)?.live ?? false, copiedGridData.find(o =&gt; o.row == cell.row - 1 &amp;&amp; o.column == cell.column)?.live ?? false, /* Left and Right */ copiedGridData.find(o =&gt; o.column == cell.column + 1 &amp;&amp; o.row == cell.row)?.live ?? false, copiedGridData.find(o =&gt; o.column == cell.column - 1 &amp;&amp; o.row == cell.row)?.live ?? false, /* Bottom Left and Right */ copiedGridData.find(o =&gt; o.column == cell.column - 1 &amp;&amp; o.row == cell.row + 1)?.live ?? false, copiedGridData.find(o =&gt; o.column == cell.column + 1 &amp;&amp; o.row == cell.row + 1)?.live ?? false, /* Top Left and Right */ copiedGridData.find(o =&gt; o.column == cell.column - 1 &amp;&amp; o.row == cell.row - 1)?.live ?? false, copiedGridData.find(o =&gt; o.column == cell.column + 1 &amp;&amp; o.row == cell.row - 1)?.live ?? false, ].filter(Boolean).length; if (adjacentCells == 3) { cell.live = true; } if (adjacentCells &lt;= 1) { cell.live = false; } if (adjacentCells &gt;= 4) { cell.live = false; } })</pre><h3>Other Control Code</h3><p>Lastly we add two more event listeners that will handle stopping and resetting the simulation and grid data.</p><pre>stopButton.addEventListener(&#39;pointerdown&#39;, () =&gt; { console.log(&#39;Stopping Simulation ...&#39;); controlsContainer.classList.remove(&#39;is_running&#39;) clearInterval(intervalId); isRunning = false; gridData = JSON.parse(savedData) renderCells(); }) resetButton.addEventListener(&#39;pointerdown&#39;, () =&gt; { gridData.map(o =&gt; o.live = false); renderCells() })</pre><h3>Styling it with CSS</h3><p>Lastly lets also go over the CSS of our little Website. We start by importing a custom font with the @font-face media rule. We can now use the name pixel for the font-family property of any element.</p><pre>@font-face { font-family: pixel; src: url(https://medium.com/font/pixel.ttf); }</pre><p>Next up we set the color-scheme property of the root element to dark which will make it so the default styling of element like scrollbar&#39;s or input is dark instead of light.</p><pre>:root { color-scheme: dark; }</pre><p>Lastly we style the playground and the cells for the playground we make use of css variables so we can avoid having to change code at different places when we want to change one thing. Also mind that we use hsl for color values since its mor obvious what color will render and we can easier make shades of colors.</p><pre>.playground { overflow: auto; padding: 1rem; flex-grow: 1; --size: 20px; display: grid; grid-template-columns: repeat(15, var(--size)); grid-auto-rows: var(--size); gap: calc(var(--size) / 10); } .cell { background-color: hsl(0, 0%, 23%); color: hsl(0, 0%, 30%); text-align: center; font-size: 0.3rem; padding:0.1rem; } .cell.live { background-color: hsl(0, 0%, 50%); }</pre><h3>Conclusion</h3><p>So thats it, I know its a lot and you may have some things that you don’t understand. I just hope that now have another Idea for a cool program that you can make. Always keep in mind that I am no pro myself just a programming enthusiast 😁.</p><p><em>Originally published at </em><a href="https://maximmaeder.com/conways-game-of-life-with-javascript/"><em>https://maximmaeder.com</em></a><em> on February 11, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=147d7fe3ac87" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>