<?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 Ahmet Ustun on Medium]]></title>
        <description><![CDATA[Stories by Ahmet Ustun on Medium]]></description>
        <link>https://medium.com/@ahmetustun?source=rss-bd1917598c2f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aqozZzfkQeUHwZPn</url>
            <title>Stories by Ahmet Ustun on Medium</title>
            <link>https://medium.com/@ahmetustun?source=rss-bd1917598c2f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:03:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmetustun/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[Understanding the Difference between oninput and onchange]]></title>
            <link>https://ahmetustun.medium.com/understanding-the-difference-between-oninput-and-onchange-c7f2c1e0e728?source=rss-bd1917598c2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7f2c1e0e728</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[events]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Ahmet Ustun]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 08:00:29 GMT</pubDate>
            <atom:updated>2024-10-04T08:00:29.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hNA4akjLXnABblT5" /><figcaption><em>Photo by </em><a href="https://unsplash.com/@taanhuyn?utm_source=medium&amp;utm_medium=referral"><em>Taan Huyn</em></a><em> on </em><a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral"><em>Unsplash</em></a></figcaption></figure><p>Responding to user input is essential when building interactive forms and dynamic user interfaces in web development. JavaScript provides several event handlers for input elements, two of the most commonly used being oninput and onchange. Both serve to detect user input, but they behave differently in terms of when they trigger and how they respond to changes in the input.</p><p>In this article, we’ll explore the differences between oninput and onchange, their use cases, and when to choose one over the other for handling user input.</p><h3><em>What is </em><em>oninput?</em></h3><p>The oninput event is triggered every time the value of an input element is modified. This event handler responds immediately to user actions such as typing, deleting, pasting, or dragging and dropping content into an input field.</p><h4><strong>Key Characteristics of </strong><strong>oninput</strong>:</h4><ul><li>Fires in real-time, i.e., on every keystroke, deletion, or content update.</li><li>Works with text input, textarea elements, and other input types like range sliders.</li><li>Allows for continuous monitoring and responding to changes as they happen.</li></ul><h4><em>Example of </em><em>oninput:</em></h4><pre>&lt;label for=&quot;username&quot;&gt;Username:&lt;/label&gt;<br>&lt;input type=&quot;text&quot; id=&quot;username&quot; oninput=&quot;updateUsername()&quot;&gt;<br><br>&lt;p id=&quot;displayUsername&quot;&gt;&lt;/p&gt;<br><br>&lt;script&gt;<br>  function updateUsername() {<br>    const usernameInput = document.getElementById(&#39;username&#39;).value;<br>    document.getElementById(&#39;displayUsername&#39;).textContent = usernameInput;<br>  }<br>&lt;/script&gt;</pre><p>In this example, every time the user types or modifies the input in the username field, the oninput event fires immediately, updating the displayed username below in real time.</p><h3>What is onchange?</h3><p>The onchange event, on the other hand, only triggers when the user commits their change. This means that the event only fires when the user leaves the input field, i.e., after it loses focus or when they press Enter and the value has changed.</p><h4><strong>Key Characteristics of </strong><strong>onchange</strong>:</h4><ul><li>Fires after the input loses focus or the value is submitted, e.g., pressing Enter in a text field.</li><li>Only triggers if the value has changed from the previous value.</li><li>Useful when you only need to act upon finalized user input.</li></ul><h4><em>Example of </em><em>onchange:</em></h4><pre>&lt;label for=&quot;email&quot;&gt;Email:&lt;/label&gt;<br>&lt;input type=&quot;email&quot; id=&quot;email&quot; onchange=&quot;validateEmail()&quot;&gt;<br><br>&lt;p id=&quot;emailMessage&quot;&gt;&lt;/p&gt;<br><br>&lt;script&gt;<br>  function validateEmail() {<br>    const emailInput = document.getElementById(&#39;email&#39;).value;<br>    <br>    if (emailInput.includes(&#39;@&#39;)) {<br>      document.getElementById(&#39;emailMessage&#39;).textContent = &quot;Valid email!&quot;;<br>    } else {<br>      document.getElementById(&#39;emailMessage&#39;).textContent = &quot;Invalid email address.&quot;;<br>    }<br>  }<br>&lt;/script&gt;</pre><p>Here, the onchange event will only fire once the user exits the input field or presses Enter after entering their email. The script validates the email only once the input process is &quot;finalized.&quot;</p><h3>Key Differences Between oninput and onchange</h3><ul><li><strong>Triggering behavior</strong><br>- oninput: Fires immediately with each change.<br>- onchange: Fires only after input loses focus or is submitted.</li><li><strong>Use case</strong><br>- oninput: Suitable for real-time feedback or monitoring.<br>- onchange: Ideal for validating or processing finalized input.</li><li><strong>Input types</strong><br>- oninput: Works on all input types that can be modified in real time.<br>- onchange: Works on all input types but fires after the user finishes interacting.</li><li><strong>Performance</strong><br>- oninput: Fires frequently, on every change, which could impact performance if used excessively in large applications.<br>- onchange: Fires less frequently, better for non-real-time, lower-performance scenarios.</li><li><strong>Validation timing</strong><br>- oninput: Can perform continuous validation or updates as the user types.<br>- onchange: Validates or updates the input only once the user is done.</li></ul><h3>Use Cases for oninput</h3><h4>Real-Time Input Validation</h4><p>If you want to provide instant feedback while the user is typing, e.g., password strength, matching fields, or live search suggestions, oninput is the best choice. This ensures that users receive immediate responses without having to wait until they finish their input.</p><h4><strong><em>Example: Password Strength Checker</em></strong></h4><pre>&lt;label for=&quot;password&quot;&gt;Password:&lt;/label&gt;<br>&lt;input type=&quot;password&quot; id=&quot;password&quot; oninput=&quot;checkPasswordStrength()&quot;&gt;<br><br>&lt;p id=&quot;passwordStrength&quot;&gt;&lt;/p&gt;<br><br>&lt;script&gt;<br>  function checkPasswordStrength() {<br>    const password = document.getElementById(&#39;password&#39;).value;<br>    const strength = password.length &gt; 8 ? &quot;Strong&quot; : &quot;Weak&quot;;<br>    document.getElementById(&#39;passwordStrength&#39;).textContent = `Password Strength: ${strength}`;<br>  }<br>&lt;/script&gt;</pre><p>In this case, as the user types their password, the strength indicator updates in real time.</p><h4>Dynamic Content Updates</h4><p>oninput is ideal for cases where you want the user interface to dynamically reflect changes based on what the user is typing or selecting. This can include auto-suggestions, live previews, or formatting updates.</p><h3>Use Cases for onchange</h3><h4>Form Submission or Final Input Validation</h4><p>In scenarios where input validation is only needed once the user has completed the input (such as forms that should only be validated before submission), onchange is a better choice. This is common for fields where the input may require concentration, and interrupting the user with live feedback may be counterproductive.</p><h4><strong>Example: Dropdown Selection Handling</strong></h4><pre>&lt;label for=&quot;country&quot;&gt;Country:&lt;/label&gt;<br>&lt;select id=&quot;country&quot; onchange=&quot;countryChanged()&quot;&gt;<br>  &lt;option value=&quot;US&quot;&gt;United States&lt;/option&gt;<br>  &lt;option value=&quot;CA&quot;&gt;Canada&lt;/option&gt;<br>  &lt;option value=&quot;UK&quot;&gt;United Kingdom&lt;/option&gt;<br>&lt;/select&gt;<br><br>&lt;p id=&quot;countryMessage&quot;&gt;&lt;/p&gt;<br><br>&lt;script&gt;<br>  function countryChanged() {<br>    const selectedCountry = document.getElementById(&#39;country&#39;).value;<br>    document.getElementById(&#39;countryMessage&#39;).textContent = `You selected: ${selectedCountry}`;<br>  }<br>&lt;/script&gt;</pre><p>Here, onchange will only fire once the user selects an option and clicks outside the select box or presses Enter.</p><h4>Reducing Unnecessary Processing</h4><p>If real-time validation or processing is unnecessary (for example, when dealing with resource-heavy operations like network requests or complex computations), onchange is more appropriate. It avoids firing the event handler on every single keystroke, thus reducing unnecessary processing.</p><h3>Performance Considerations</h3><p>Since oninput fires with every change, it can introduce performance overhead if you’re handling complex operations or updating the DOM frequently. For instance, if you&#39;re validating a form field that requires significant computation or server requests on every keystroke, oninput might cause performance degradation, especially in slower environments.</p><p>onchange is less resource-intensive as it only triggers after the user commits the change. If performance is a concern and real-time feedback is unnecessary, onchange should be the preferred choice.</p><h3>When to Use oninput vs onchange</h3><ul><li>Use oninput when you need real-time feedback or immediate responses to user input. It’s suitable for scenarios like form field validation, live search, dynamic content updates, or interactive features like password strength checking.</li><li>Use onchange when you only need to act upon the user&#39;s final input, such as after they finish typing or selecting a value. It&#39;s perfect for scenarios where validating or processing every input is unnecessary, such as drop-down menus, form submissions, or settings adjustments.</li></ul><h3>Conclusion</h3><p>Both oninput and onchange are useful event handlers for different scenarios in web development. Understanding their key differences helps ensure you provide a smoother user experience and optimize your web application&#39;s performance.</p><p>Use oninput for real-time input handling, and onchange when working with final or committed input. Choosing the right event can enhance the interactivity and responsiveness of your web applications while maintaining efficient performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7f2c1e0e728" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring MutationObserver for Monitoring DOM Changes]]></title>
            <link>https://ahmetustun.medium.com/exploring-mutationobserver-for-monitoring-dom-changes-f0e071719e44?source=rss-bd1917598c2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0e071719e44</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ahmet Ustun]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 11:31:45 GMT</pubDate>
            <atom:updated>2024-09-27T11:31:45.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jzBRSGJFglpn9c5l" /><figcaption>Photo by <a href="https://unsplash.com/@vingtcent?utm_source=medium&amp;utm_medium=referral">Vincent Guth</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Modern web applications often involve dynamic content that updates in real-time. As web pages grow more interactive, developers need tools to keep track of changes in the Document Object Model (DOM) to react to user interactions, updates, or content changes. One such tool is the MutationObserver, a powerful API that allows developers to watch for changes in the DOM and respond programmatically when they occur.</p><p>In this article, we’ll explore what MutationObserver is, why it&#39;s useful, and how to use it effectively in web development.</p><h3>What is MutationObserver?</h3><p>MutationObserver is a built-in JavaScript API that allows developers to monitor changes in the DOM tree. It provides a way to observe specific nodes and listen for mutations such as:</p><ul><li>Changes to the node’s attributes</li><li>Additions or removals of child nodes</li><li>Modifications to the text content of the node or its descendants</li></ul><blockquote>Before MutationObserver, developers relied on MutationEvent, which was both inefficient and had performance issues. MutationObserver offers a more performant, flexible, and efficient alternative, making it the go-to method for monitoring DOM changes in modern web applications.</blockquote><h3>Why use MutationObserver?</h3><p>MutationObserver is particularly useful in situations where you need to detect changes to the structure or attributes of a webpage, especially when the DOM is being modified dynamically. Here are some key reasons why MutationObserver can be beneficial:</p><h4>Real-Time Monitoring of Dynamic Content</h4><p>Many web apps today use dynamic content loading (e.g., single-page applications, infinite scroll, or real-time updates from APIs). Using MutationObserver, you can monitor changes to a specific DOM element or section of the page and react to these changes programmatically.</p><h4>Performance Efficiency</h4><p>MutationObserver is designed to efficiently observe DOM mutations. Unlike the older MutationEvent API, which triggered an event for every change, MutationObserver batches mutations into a single callback. This reduces the performance impact on the page, especially for apps that handle frequent DOM updates.</p><h4>Interactivity &amp; User Experience</h4><p>MutationObserver can be used to enhance user interactions by dynamically updating UI components in response to changes in other parts of the DOM. For example, if a user submits a form and the result updates the page, you can observe those changes and automatically update related elements.</p><h4>Automated Testing</h4><p>In some scenarios, developers use MutationObserver in automated testing to ensure that certain actions result in specific DOM changes. This can be particularly helpful for end-to-end testing frameworks that require detecting DOM updates without directly interacting with the internal code.</p><h3>How to Use MutationObserver</h3><p>Setting up a MutationObserver involves creating a new observer instance, passing a callback function that handles the mutations, and configuring the types of mutations you want to monitor.</p><h4>Syntax</h4><pre>const observer = new MutationObserver(callback);<br>observer.observe(targetNode, config);</pre><ul><li>callback: A function that is called when mutations are detected. It receives a list of MutationRecord objects.</li><li>targetNode: The DOM node to observe.</li><li>config: An object specifying what types of mutations to observe (e.g., childList, attributes, etc.).</li></ul><h4>Example 1: Monitoring Child Node Additions and Removals</h4><p>Let’s observe changes to a list of items. We want to detect when new items are added or removed from the list:</p><pre>&lt;ul id=&quot;itemList&quot;&gt;<br>  &lt;li&gt;Item 1&lt;/li&gt;<br>  &lt;li&gt;Item 2&lt;/li&gt;<br>&lt;/ul&gt;<br><br>&lt;button id=&quot;addItem&quot;&gt;Add Item&lt;/button&gt;</pre><pre>// Select the target node (the list element)<br>const targetNode = document.getElementById(&#39;itemList&#39;);<br>const addItemBtn = document.getElementById(&#39;addItem&#39;);<br><br>// Define the mutation observer callback<br>const callback = function(mutationsList, observer) {<br>    for (let mutation of mutationsList) {<br>        if (mutation.type === &#39;childList&#39;) {<br>            console.log(&#39;A child node has been added or removed.&#39;);<br>        }<br>    }<br>};<br><br>// Create an observer instance<br>const observer = new MutationObserver(callback);<br><br>// Specify the mutation types to observe<br>const config = { childList: true };<br><br>// Start observing the target node<br>observer.observe(targetNode, config);<br><br>// Example of adding a new item to the list dynamically<br>addItemBtn.addEventListener(&#39;click&#39;, function() {<br>    const newItem = document.createElement(&#39;li&#39;);<br>    newItem.textContent = `Item ${targetNode.children.length + 1}`;<br>    targetNode.appendChild(newItem);<br>});</pre><p>In this example, every time a new list item is added or removed, the callback logs a message to the console.</p><h4>Example 2: Observing Attribute Changes</h4><p>You might want to monitor changes to an element’s attributes. Here’s an example where we observe an element’s class attribute:</p><pre>&lt;div id=&quot;myElement&quot; class=&quot;inactive&quot;&gt;Click to Activate&lt;/div&gt;<br><br>&lt;button id=&quot;toggleClass&quot;&gt;Toggle Class&lt;/button&gt;</pre><pre>// Select the target node<br>const targetNode = document.getElementById(&#39;myElement&#39;);<br>const toggleClassBtn = document.getElementById(&#39;toggleClass&#39;);<br><br>// Callback function to execute when mutations are observed<br>const callback = function(mutationsList, observer) {<br>    for (let mutation of mutationsList) {<br>        if (mutation.type === &#39;attributes&#39; &amp;&amp; mutation.attributeName === &#39;class&#39;) {<br>            console.log(`Class attribute changed to: ${mutation.target.getAttribute(&#39;class&#39;)}`);<br>        }<br>    }<br>};<br><br>// Create a new MutationObserver instance<br>const observer = new MutationObserver(callback);<br><br>// Define the configuration to observe attribute changes<br>const config = { attributes: true };<br><br>// Start observing<br>observer.observe(targetNode, config);<br><br>// Button to toggle class<br>toggleClassBtn.addEventListener(&#39;click&#39;, function() {<br>    if (targetNode.classList.contains(&#39;inactive&#39;)) {<br>        targetNode.classList.remove(&#39;inactive&#39;);<br>        targetNode.classList.add(&#39;active&#39;);<br>    } else {<br>        targetNode.classList.remove(&#39;active&#39;);<br>        targetNode.classList.add(&#39;inactive&#39;);<br>    }<br>});</pre><p>Here, every time the button is clicked and the class attribute of the div is changed, the MutationObserver logs the updated class.</p><h4>Example 3: Disconnecting the Observer</h4><p>Sometimes, you may want to stop observing after certain conditions are met or to prevent performance degradation in large applications. You can stop observing using the disconnect() method:</p><pre>// Stop observing mutations<br>observer.disconnect();</pre><h3>MutationObserver Configuration Options</h3><p>The observe method accepts a configuration object that defines which mutations to watch for. Key properties include:</p><ul><li>childList: Set to true to observe additions and removals of child nodes.</li><li>attributes: Set to true to observe changes to attributes.</li><li>subtree: Set to true to observe changes in the entire subtree of the target node.</li><li>characterData: Set to true to observe changes to the text content of the target node.</li></ul><p>Here’s an example configuration that monitors changes in child nodes, attributes, and character data in the entire subtree of the target node:</p><pre>const config = {<br>    childList: true,<br>    attributes: true,<br>    characterData: true,<br>    subtree: true<br>};</pre><h3>Limitations of MutationObserver</h3><p>Despite its usefulness, MutationObserver has a few limitations:</p><ul><li><strong>No Deep Attribute Monitoring:</strong> While MutationObserver can detect attribute changes, it doesn’t track the actual values before and after the change. You need to manually retrieve the new value using getAttribute().</li><li><strong>Performance Overhead:</strong> Monitoring large portions of the DOM, or complex mutation events can result in performance overhead. Always be selective about the types of mutations and nodes you are observing to avoid slowing down the app.</li><li><strong>No Support for Non-DOM Changes:</strong> MutationObserver only tracks DOM changes. It doesn’t track changes to variables, data models, or non-DOM properties.</li></ul><h3>Best Practices for Using MutationObserver</h3><ul><li><strong>Limit Scope</strong>: Only observe specific nodes and events that are critical. Avoid monitoring the entire document unless absolutely necessary.</li><li><strong>Batch DOM Updates</strong>: Since MutationObserver batches changes, try to group updates and make fewer modifications to the DOM.</li><li><strong>Disconnect When Necessary</strong>: Use disconnect() to stop observing when you no longer need to monitor a node. This prevents unnecessary resource usage.</li><li><strong>Test for Performance Impact</strong>: If you’re using MutationObserver in a high-interaction web app, periodically test for performance issues, especially in complex scenarios.</li></ul><h3>Conclusion</h3><p>MutationObserver is an invaluable tool for web developers building dynamic and interactive web applications. By offering efficient, real-time monitoring of DOM changes, it helps developers respond to updates, track changes, and automate processes. With its flexibility and performance benefits, it’s become a standard API for handling dynamic DOM operations. By following best practices and leveraging MutationObserver intelligently, you can ensure your applications remain responsive and efficient even as the complexity of your web pages grows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0e071719e44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding navigator.sendBeacon for Efficient Data Transmission]]></title>
            <link>https://blog.stackademic.com/understanding-navigator-sendbeacon-for-efficient-data-transmission-fc635a96ce9e?source=rss-bd1917598c2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc635a96ce9e</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ahmet Ustun]]></dc:creator>
            <pubDate>Fri, 20 Sep 2024 14:17:24 GMT</pubDate>
            <atom:updated>2024-09-25T20:23:00.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2Jf0VBm2MjJ66vw5" /><figcaption>Photo by <a href="https://unsplash.com/@antilumen?utm_source=medium&amp;utm_medium=referral">Robert Wiedemann</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the modern web ecosystem, user interactions are often tracked and analyzed to optimize user experience, improve performance, and gather insights. However, sending data to a server in certain contexts can be challenging, especially when the timing is crucial. That’s where navigator.sendBeacon comes into play, a method designed to reliably and efficiently send small amounts of data to a server, even when a page is unloading.</p><p>In this article, we’ll dive into what navigator.sendBeacon is, why it&#39;s useful, and how to implement it effectively in web applications.</p><h3>What is navigator.sendBeacon?</h3><p>navigator.sendBeacon is a web API method that allows web pages to send small chunks of data to a server asynchronously. It is specifically designed to work in scenarios where the page is being unloaded, such as when a user navigates away from the page or closes the browser. Unlike other methods like XMLHttpRequest or fetch, which might fail or get canceled during these transitions, navigator.sendBeacon is built to handle such cases more reliably.</p><p><strong>Key characteristics</strong> of navigator.sendBeacon:</p><ul><li>It sends data asynchronously.</li><li>It operates in the background, without blocking the main thread.</li><li>It is designed for scenarios where the page is being unloaded (i.e., navigating away, closing, etc.).</li></ul><blockquote>The browser ensures the data is transmitted even during the page’s unload event.</blockquote><h3>Why use navigator.sendBeacon?</h3><p>Here are some typical use cases and reasons for utilizing navigator.sendBeacon in web development:</p><h4>Reliable Data Transmission on Unload</h4><p>One of the primary uses for navigator.sendBeacon is to send analytics data or logs when a user leaves the page. Traditional methods like XMLHttpRequest or fetch often fail in these contexts because the browser can terminate the connection as the page unloads. navigator.sendBeacon ensures that the data reaches the server even if the user closes the tab or navigates to another page.</p><h4>Non-blocking Operations</h4><p>Unlike synchronous requests that can delay or block user interactions (for example, waiting for a network request to complete), navigator.sendBeacon operates asynchronously and doesn’t block the page. This makes it an ideal candidate for transmitting non-critical data that shouldn&#39;t interfere with the user experience.</p><h4>Efficiency</h4><p>Since navigator.sendBeacon operates in the background and doesn&#39;t require the browser to keep the connection open for an extended period, it&#39;s more efficient in scenarios where the precise timing of the transmission isn&#39;t critical. This can lead to improved performance, especially when compared to other methods that might delay navigation or other user actions.</p><h4>Analytics and Tracking</h4><p>Web applications often need to track events like user interactions, performance metrics, or error logging. navigator.sendBeacon allows developers to ensure that such information is reliably transmitted, even if it occurs just before a page unloads.</p><h3>How to use navigator.sendBeacon</h3><p>Implementing navigator.sendBeacon is straightforward. Here’s a simple syntax and an example:</p><h4>Syntax:</h4><pre>navigator.sendBeacon(url, data);</pre><ul><li>url: The URL of the server where the data is sent.</li><li>data: The data to be sent, which can be in various formats like a string, Blob, ArrayBufferView, FormData, or URLSearchParams.</li></ul><h4>Example 1: Sending Analytics Data on Page Unload</h4><p>Suppose you want to send user activity data just before they leave the page:</p><pre>window.addEventListener(&#39;beforeunload&#39;, function (event) {<br>    const url = &quot;/track-user-activity&quot;;<br>    const data = JSON.stringify({ event: &quot;pageUnload&quot;, timestamp: Date.now() });<br>    navigator.sendBeacon(url, data);<br>});</pre><p>In this case, the beforeunload event captures the moment just before the page is unloaded, and navigator.sendBeacon transmits the user’s activity to the server. The browser handles the transmission in the background, ensuring that the data reaches its destination even as the page closes.</p><h4>Example 2: Logging Errors</h4><p>You might also want to use navigator.sendBeacon to report errors or performance metrics:</p><pre>window.addEventListener(&#39;error&#39;, function (event) {<br>    const url = &quot;/log-error&quot;;<br>    const errorData = {<br>        message: event.message,<br>        source: event.filename,<br>        lineno: event.lineno,<br>        colno: event.colno,<br>        time: new Date().toISOString()<br>    };<br>    <br>    navigator.sendBeacon(url, JSON.stringify(errorData));<br>});</pre><p>Here, if an error occurs, the error information is sent to the server using navigator.sendBeacon. This ensures error logging is reliable even if the error happens shortly before the user leaves the page.</p><h3>Limitations of navigator.sendBeacon</h3><p>While navigator.sendBeacon is a powerful tool, it has its limitations:</p><ul><li><strong>Small Payloads:</strong> navigator.sendBeacon is best suited for sending small amounts of data. Browsers may enforce limits on the size of the payload (typically around 64 KB). If the payload is too large, the transmission might fail.</li><li><strong>One-way Communication:</strong> Unlike fetch or XMLHttpRequest, navigator.sendBeacon doesn&#39;t provide a way to receive a response from the server. This makes it useful for &quot;fire-and-forget&quot; data transmission where a response isn&#39;t required.</li><li><strong>Unsupported in Some Older Browsers:</strong> While navigator.sendBeacon is widely supported in modern browsers, older browsers (such as Internet Explorer) may not support it, so you may need to include fallbacks for those cases.</li><li><strong>Network Congestion:</strong> Though navigator.sendBeacon is designed to be reliable, if the user has network issues or disconnects immediately after leaving the page, the data might not be sent. However, this is rare, and browsers generally make a best-effort attempt to send the data.</li></ul><h3>Best Practices for Using navigator.sendBeacon</h3><p>To make the most of navigator.sendBeacon, here are some tips:</p><ul><li><strong>Limit Payload Size</strong>: Since navigator.sendBeacon works best with small amounts of data, ensure you don’t overload it with large payloads. If necessary, batch your data or send it incrementally.</li><li><strong>Combine with Other Methods</strong>: For critical data that needs confirmation of receipt, you might want to use fetch or XMLHttpRequest for regular data transmission and reserve navigator.sendBeacon for &quot;last-chance&quot; transmissions during the unload event.</li><li><strong>Use for Low-Priority Data</strong>: navigator.sendBeacon is perfect for low-priority tasks like logging, analytics, or performance tracking. For critical, user-facing actions (like submitting a form), use more reliable and immediate methods like fetch.</li></ul><h3>Conclusion</h3><p>navigator.sendBeacon is a valuable addition to the web developer&#39;s toolkit, providing a reliable, efficient, and non-blocking way to send data to the server. Whether you&#39;re handling analytics, error logging, or performance monitoring, navigator.sendBeacon ensures that important data is sent, even as the page unloads. By understanding its use cases and limitations, you can implement it effectively in your web applications to enhance both user experience and application performance.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc635a96ce9e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/understanding-navigator-sendbeacon-for-efficient-data-transmission-fc635a96ce9e">Understanding navigator.sendBeacon for Efficient Data Transmission</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Downloading React Components as PDF Files]]></title>
            <link>https://blog.stackademic.com/downloading-a-react-component-as-pdf-12021aaf0ccc?source=rss-bd1917598c2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/12021aaf0ccc</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[pdf-download]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Ahmet Ustun]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 07:43:44 GMT</pubDate>
            <atom:updated>2024-09-26T12:46:07.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Close up of a video game controller" src="https://cdn-images-1.medium.com/max/1024/1*7sbeVdsSNbZb_S0Alf60Vg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@senadpalic?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Senad Palic</a> on <a href="https://unsplash.com/photos/a-close-up-of-a-video-game-controller-bWYZn--b48I?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Users may need a way to download a specific part of the UI as a PDF file. This can include tickets, bills, or shopping lists. It’s a convenient way for them if they want to print such documents.</p><p>Recently, I had to create a button that would let our users download a list of item-specific configurations set by themselves. I was supposed to do this in the most economical way possible for performance concerns. I started researching for any React libraries to help me in this journey. I found quite a few options, yet all of them were unnecessarily vast for my use case.</p><p><a href="https://differ.blog/differ-ai">Introducing DifferAI</a></p><p><strong>TL;DR —</strong> Most probably you have encountered articles that would recommend the combination of <a href="https://github.com/niklasvh/html2canvas">html2canvas</a> and <a href="https://github.com/parallax/jsPDF">jsPDF</a>. Even though they’re very good libraries, you may not need them for such a narrow use case. In this article, I will talk about <a href="https://github.com/ivmarcos/react-to-pdf">react-to-pdf</a> (ver. 1.0.1), a concise library for downloading React components as PDF files. Please be aware that PDFs are generated from component screenshots and there is no Server-Side Rendering (SSR) supported.</p><h3>Search for a Library</h3><p>I started my research with some articles and as well as I asked ChatGPT for a way to download React components as PDF files. Both ways ended up that I should use html2canvas and jsPDF.</p><p>The overall logic of using these 2 libraries is converting the rendered component to an <a href="https://www.w3schools.com/html/html5_canvas.asp">HTML canvas</a>, embedding it into a PDF file, and downloading it.</p><p>As I mentioned earlier, I had to make an economic decision. Although <a href="https://www.npmjs.com/package/jspdf/v/2.5.1">jsPDF</a> has only 8 dependencies (one is html2canvas), the unpacked size is 14.7 MB as of version 2.5.1.</p><figure><img alt="Details about jsPDF from the npm page" src="https://cdn-images-1.medium.com/max/393/1*D8qaqPPhfXbRSBLvX6nFOg.png" /><figcaption>Details about jsPDF (ver. 2.5.1)</figcaption></figure><p>In the end, I could get the green light only for jsPDF since html2canvas is one of the dependencies and my team thought it wouldn’t be necessary to install it additionally.</p><figure><img alt="Dependencies of jsPDF from the npm page" src="https://cdn-images-1.medium.com/max/705/1*yf92TNSH37QFg3Dofj5zyA.png" /><figcaption>Dependencies of jsPDF (ver. 2.5.1)</figcaption></figure><h3>Issues along the Way</h3><p>I should say that jsPDF has detailed documentation and I had no issues there. As my task was to download a specific component as a PDF file, the html method came to my rescue (or this is what I thought).</p><p>Below is an example of the usage of the html method from the documentation:</p><pre>var doc = new jsPDF();<br><br>doc.html(document.body, {<br>   callback: function (doc) {<br>     doc.save();<br>   },<br>   x: 10,<br>   y: 10<br>});</pre><p>Initially, it worked well with some tweaking of scaling and positioning the component in the PDF file. However, I had an issue since our project has custom fonts, and porting them to PDFs required extra effort such.</p><p>This approach turned the rendered HTML content with its styling (except the fonts) to be used in the PDF structure. I was expecting it to create a screenshot of the component and embed it in the PDF file though.</p><p>At this point, I had to find another library for my narrow use case.</p><h3>Finding react-to-pdf</h3><p>After some research, I came across react-to-pdf. When I was checking some of the library details such as unpacked size and amount of dependencies, I knew that I had to give it a try.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*go1zZ7OhSblIt64DdQkKeA.png" /><figcaption>Details about react-to-pdf (ver. 1.0.1)</figcaption></figure><p>Before I jump into the implementation, I want to mention that it was surprising to see that <a href="https://www.npmjs.com/package/react-to-pdf/v/1.0.1">react-to-pdf</a> has only 2 dependencies and its unpacked size is 82.7 kB as of version 1.0.1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*m3mhXwiA-x4pQQJLE8d6zg.png" /><figcaption>Dependencies of react-to-pdf (ver. 1.0.1)</figcaption></figure><p>After looping through some different ways to use html2canvas and jsPDF, they were right in front of me as the 2 sole dependencies.</p><h3>Using react-to-pdf</h3><p>You can install react-to-pdf with yarn or npm:</p><pre># Yarn<br>yarn add react-to-pdf<br><br># NPM<br>npm install --save react-to-pdf</pre><p>Please be aware that PDFs are generated from component screenshots. Also, note that there is no Server-Side Rendering (SSR) supported. If you’re building in frameworks such as Next.js, you can use react-to-pdf in client components.</p><p>In terms of usage, there are 2 ways to generate PDFs: usePDF hook and default function provided from react-to-pdf.</p><p>Here is how you can use the usePDF hook:</p><pre>import { usePDF } from &#39;react-to-pdf&#39;;<br><br>const Component = () =&gt; {<br>   const { toPDF, targetRef } = usePDF({filename: &#39;page.pdf&#39;});<br>   return (<br>      &lt;div&gt;<br>         &lt;button onClick={() =&gt; toPDF()}&gt;Download PDF&lt;/button&gt;<br>         &lt;div ref={targetRef}&gt;<br>            Content to be generated to PDF<br>         &lt;/div&gt;<br>      &lt;/div&gt;<br>   )<br>}</pre><p>Here is how you can use the default function:</p><pre>import { useRef } from &#39;react&#39;;<br>import generatePDF from &#39;react-to-pdf&#39;;<br><br>const Component = () =&gt; {<br>   const targetRef = useRef();<br>   return (<br>      &lt;div&gt;<br>         &lt;button onClick={() =&gt; generatePDF(targetRef, {filename: &#39;page.pdf&#39;})}&gt;<br>            Download PDF<br>         &lt;/button&gt;<br>         &lt;div ref={targetRef}&gt;<br>            Content to be included in the PDF<br>         &lt;/div&gt;<br>      &lt;/div&gt;<br>   )<br>}</pre><p>You can also pass some options if you want to take a step further:</p><pre>import generatePDF, { Resolution, Margin } from &#39;react-to-pdf&#39;;<br><br>const options = {<br>   // default is `save`<br>   method: &#39;open&#39;,<br>   // default is Resolution.MEDIUM = 3, which should be enough, higher values<br>   // increases the image quality but also the size of the PDF, so be careful<br>   // using values higher than 10 when having multiple pages generated, it<br>   // might cause the page to crash or hang.<br>   resolution: Resolution.HIGH,<br>   page: {<br>      // margin is in MM, default is Margin.NONE = 0<br>      margin: Margin.SMALL,<br>      // default is &#39;A4&#39;<br>      format: &#39;letter&#39;,<br>      // default is &#39;portrait&#39;<br>      orientation: &#39;landscape&#39;,<br>   },<br>   canvas: {<br>      // default is &#39;image/jpeg&#39; for better size performance<br>      mimeType: &#39;image/png&#39;,<br>      qualityRatio: 1<br>   },<br>   // Customize any value passed to the jsPDF instance and html2canvas<br>   // function. You probably will not need this and things can break, <br>   // so use with caution.<br>   overrides: {<br>      // see https://artskydj.github.io/jsPDF/docs/jsPDF.html for more options<br>      pdf: {<br>         compress: true<br>      },<br>      // see https://html2canvas.hertzen.com/configuration for more options<br>      canvas: {<br>         useCORS: true<br>      }<br>   },<br>};<br><br>// you can use a function to return the target element besides using React refs<br>const getTargetElement = () =&gt; document.getElementById(&#39;content-id&#39;);<br><br>const Component = () =&gt; {<br>   return (<br>      &lt;div&gt;<br>         &lt;button onClick={() =&gt; generatePDF(getTargetElement, options)}&gt;<br>            Generate PDF<br>         &lt;/button&gt;<br>         &lt;div id=&quot;content-id&quot;&gt;<br>            Content to be generated to PDF<br>         &lt;/div&gt;<br>      &lt;/div&gt;<br>   );<br>}</pre><p><a href="https://codesandbox.io/p/sandbox/billowing-fog-lq4xj6">Here</a> is a demo provided in the react-to-pdf documentation via Code Sandbox. I would also like to mention that the code blocks above are also from the documentation.</p><h3>Conclusion</h3><p>Like me, you may need to let your users download PDF files generated from components. There are several ways to do this when you check some other resources.</p><p>In this article, I focused on react-to-pdf since I liked its lightweight structure and simple usage. I hope this article helps you achieve if you have a similar task.</p><h3>Resources</h3><ul><li><a href="https://raw.githack.com/MrRio/jsPDF/master/docs/index.html">jsPDF Documentation</a></li><li><a href="https://html2canvas.hertzen.com/documentation">html2canvas Documentation</a></li><li><a href="https://github.com/ivmarcos/react-to-pdf">react-to-pdf GitHub Page</a></li></ul><blockquote><em>👉 </em><strong>Also learn these 11 useful React tips and tricks to boost your web development skills:</strong></blockquote><p><a href="https://differ.blog/inplainenglish/11-useful-react-js-hack-every-developer-should-know-8debac">11 Useful React.js Hack Every Developer Should Know</a></p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12021aaf0ccc" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/downloading-a-react-component-as-pdf-12021aaf0ccc">Downloading React Components as PDF Files</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Listing the Globally Installed NPM Packages]]></title>
            <link>https://ahmetustun.medium.com/listing-the-globally-installed-npm-packages-b81fae4bf391?source=rss-bd1917598c2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b81fae4bf391</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Ahmet Ustun]]></dc:creator>
            <pubDate>Fri, 21 Apr 2023 09:31:43 GMT</pubDate>
            <atom:updated>2023-04-21T09:37:40.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euyZGDxaNgUcgMFeZc2N-Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@carltraw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Carl Raw</a> on <a href="https://unsplash.com/photos/m3hn2Kn5Bns?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When working with Node.js, you may install various NPM packages globally to use them across multiple projects. Over time, you may forget which global NPM packages are on your system.</p><p>In this article, we’ll explore how to list the global NPM packages on your system with code samples.</p><h3>Listing the Global NPM Packages</h3><p>To list the installed global NPM packages, you can use the following command in your terminal:</p><pre># List the installed global NPM packages<br>npm list -g --depth 0</pre><p>This command will display the list of global NPM packages installed on your system.</p><ul><li>-g or --global: The option to list global packages on your system.</li><li>--depth 0: The option to limit the depth of the dependency tree to zero. This will only list the top-level packages without their dependencies.</li></ul><h3>Listing the Global NPM Packages with Details</h3><p>To list the installed global NPM packages with details, such as the version number and location, you can use the following command:</p><pre># List the installed global NPM packages with details<br>npm list -g --depth 0 --long</pre><p>This command will display the list of global NPM packages installed on your system along with their version number and installation location.</p><ul><li>--long: The option to display additional information about each package, including its version and the location of its files on disk.</li></ul><h3>Checking the Version of a Global NPM Package</h3><p>To check the version of a specific global NPM package, you can use the following command:</p><pre># Check the version of a specific global NPM package<br>npm list -g &lt;package_name&gt;</pre><p>Replace &lt;package_name&gt; with the name of the global NPM package you want to check.</p><pre>npm list -g create-react-app</pre><h3>Conclusion</h3><p>Listing the global NPM packages on your system is a simple process that can help you keep track of the NPM packages installed on your system.</p><p>Remember to periodically check the list of global NPM packages to keep your system up-to-date and avoid any conflicts or issues with your projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b81fae4bf391" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Changing the Remote URL in a Git Repository]]></title>
            <link>https://ahmetustun.medium.com/changing-remote-in-git-repositories-2a1ebda0f0e0?source=rss-bd1917598c2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a1ebda0f0e0</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Ahmet Ustun]]></dc:creator>
            <pubDate>Wed, 19 Apr 2023 06:39:35 GMT</pubDate>
            <atom:updated>2023-04-21T08:46:09.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Vintage gray game console with joysticks" src="https://cdn-images-1.medium.com/max/1024/1*eNiQG0u2bcQsciKS8zCw-w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lorenzoherrera?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lorenzo Herrera</a> on <a href="https://unsplash.com/photos/p0j-mE6mGo4?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Git is a powerful version control system that allows developers to collaborate on code and track changes made to a project over time.</p><p>Sometimes, you may need to change the remote URL associated with a Git repository. In this article, we’ll explore how to change the remote URL of a Git repository with code samples.</p><h3>Checking the Current Remote URL</h3><p>Before changing the remote URL, it’s essential to verify the current remote URL associated with your Git repository.</p><p>You can do this by using the following command:</p><pre># Verify the current remote URL<br>git remote -v</pre><p>This command will display the current remote URL associated with your Git repository.</p><h3>Adding a New Remote URL</h3><p>To add a new remote URL to your Git repository, you can use the following command:</p><pre># Add a new remote URL<br>git remote add &lt;name&gt; &lt;URL&gt;</pre><p>Replace &lt;name&gt; with a name for your new remote and &lt;URL&gt; with the URL of your new remote repository.</p><pre>git remote add newRemote https://github.com/user/newrepo.git</pre><h3>Removing an Old Remote URL</h3><p>To remove an old remote URL from your Git repository, you can use the following command:</p><pre># Remove an old remote URL<br>git remote rm &lt;name&gt;</pre><p>Replace &lt;name&gt; with the name of the old remote repository, you want to remove.</p><pre>git remote rm oldRemote</pre><h3>Setting a New Remote URL as Default</h3><p>To set a new remote URL as the default for your Git repository, you can use the following command:</p><pre># Set a new remote URL as default<br>git remote set-url origin &lt;URL&gt;</pre><p>Replace &lt;URL&gt; with the URL of your new remote repository.</p><pre>git remote set-url origin https://github.com/user/newrepo.git</pre><h3>Conclusion</h3><p>Changing the remote URL of a Git repository can be done easily with the right commands without losing any of your existing code.</p><p>Make sure to check the current remote URL before making any changes, and set the new remote URL as default to avoid any confusion in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a1ebda0f0e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>