DEV Community: Hamza Ali The latest articles on DEV Community by Hamza Ali (@hat52). https://dev.to/hat52 https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F670194%2F6139173a-7549-47e2-8125-f1918154f499.jpeg DEV Community: Hamza Ali https://dev.to/hat52 en Ensuring Data Consistency in Concurrent API Requests: Introducing the AbortController Hamza Ali Sun, 14 May 2023 06:31:28 +0000 https://dev.to/hat52/ensuring-data-consistency-in-concurrent-api-requests-introducing-the-abortcontroller-27bh https://dev.to/hat52/ensuring-data-consistency-in-concurrent-api-requests-introducing-the-abortcontroller-27bh <p>Let's say you are working on a project and in that project you want to get the data of the user's friends. Let's say you requested to fetch the data of Adam's friends. But Adam has a lot of friends so the API request takes time to fetch the list of friends. Now before the API has responded you decided that you want to fetch the friend list of Eve and Eve's friend list is short so the API responded quickly with the friend list of Eve and now as the API responded you display the data on the screen. But wait what about the API request of Adam's friend's list? As the API call is in progress when this API is going to complete it will override the result of Eve's friend list and instead of showing the right data we will be displaying the data of Adam's friends instead of Eve's.</p> <p>You see the bug in the above explanation. So to get rid of the bug we need to abort the API of Adam's friend list. There are many ways to achieve this but for this blog, I will cover the AbortController.</p> <p>AbortController</p> <p>The AbortController interface represents a controller object that allows you to abort one or more Web requests as and when desired.</p> <p>We will use the AbortController in the use effect like this </p> <p>useEffect(() =&gt; {<br> const controller = new AbortController();<br> const signal = controller.signal;</p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>fetch('my-resource', { signal }) .then(res =&gt; res.json()) .then(res =&gt; setFriendsList(res)) .catch(console.log); return () =&gt; controller.abort(); </code></pre> </div> <p>}, []);</p> <p>But how exactly this AbortController works? </p> <p>When the abort method on the controller is called, the fetch operation and every subsequent then methods are discarded, and the catch method is executed. </p> <p>If you are doing anything in the catch block, then you might need to add a new check to make sure that you set the errors in the right scenario. So to check if the API is aborted mid execution you can check if controller.abort.signal is set to true, If it is then the API is aborted mid-execution.</p> <p>Happy hacking!</p> javascript webdev programming api Detecting clicks outside an HTML element using the custom React Hook Hamza Ali Sat, 11 Feb 2023 14:29:46 +0000 https://dev.to/hat52/detecting-clicks-outside-an-html-element-using-the-custom-react-hook-4314 https://dev.to/hat52/detecting-clicks-outside-an-html-element-using-the-custom-react-hook-4314 <p>In February 2019 React introduced Hooks. Which empowered the Functional components to have the same powers/features which were only present in React Class component before <strong>React 16.8.0</strong>. The introduction of hooks gave function components the ability to use state and side-effects with built-in Hooks such as <a href="proxy.php?url=https://reactjs.org/docs/hooks-state.html">React's useState Hook</a> and <a href="proxy.php?url=https://reactjs.org/docs/hooks-effect.html">React's useEffect Hook</a>.</p> <p>There are only a handful of built-in hooks in React. However, react also give the developer the option to develop their own Hooks which react states as <strong>Custom Hooks.</strong> By using the Hooks provided by react as a foundation developers can develop their own hooks that can contain stateful logic.</p> <p>Before we create a custom hook, you need to know that there are two rules to creating one:</p> <ul> <li>Custom hooks must have "use" as a prefix. It is how React knows to start the logic contained in the Hook and make the returned state and values available to the component. For example useLocalStorage or useBoolean etc. In our case, the custom hook will be named <strong>useOutSideClick</strong>.</li> <li>The custom hook is built using built-in React hooks. Therefore custom hook is always a new composition of one or multiple hooks. If a hook doesn't use any hook then it's not a custom hook It will just be a plain javascript function. So in short if you want to create a custom hook then you should use React hooks inside of it.</li> </ul> <p>To explain further what custom hooks are I am going to create a custom hook that will detect if a click has happened outside of an HTML element or a react component.</p> <h3> Implementing the Hook </h3> <p>we are going to create a hook that is going to detect if a click has occurred outside the desired component. This kind of hook is really useful when you are building a Dropdown component, menu or modal. You want to close the window when a click has occurred outside of the modal.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>import { MutableRefObject, useEffect } from 'react'; type OutsideNotifierHook = ( ref: MutableRefObject&lt;any&gt;, onOutsideClick: (isInside: false) =&gt; void ) =&gt; void; const useOutSideClick: OutsideNotifierHook = (ref, onOutsideClick) =&gt; { useEffect(() =&gt; { const handleClick = (e: MouseEvent) =&gt; { if (ref.current &amp;&amp; !ref.current.contains(e.target)) { onOutsideClick(false); } }; document.addEventListener('mousedown', handleClick); return () =&gt; document.removeEventListener('mousedown', handleClick); }, [ref, onOutsideClick]); }; export default useOutSideClick; </code></pre> </div> <p>The code defines a custom hook named <strong>useOutSideClick</strong>. The Hook allows you to detect clicks outside a specified HTML element and trigger a callback when this occurs.</p> <p>The hook takes two arguments, <strong>ref</strong> and <strong>onOutSideClick</strong>.</p> <ul> <li> <strong>ref:</strong> ref is of type MutableRefObject that refers to the HTML element you want to track the outside click.</li> <li> <strong>onOutSideClick:</strong> this is a callback function that is fired when the click has occurred outside of the element passed as the first argument.</li> </ul> <p><strong>useEffect</strong> hook is used to handle the side effect of the component. In this case, add and remove the mouse event listener to the document object.</p> <p><strong>handleClick</strong> function is defined in the useEffect which is passed as the second argument to the event listener. This means that it is going to be triggered when the outside click will occur. It will also determine if the click has occurred outside or inside the <strong>ref</strong> argument. If the click has occurred outside of the <strong>ref</strong> argument then it will trigger the callback with <strong>false</strong> as an argument.</p> <p>The <strong>return</strong> argument in the useEffect is to remove the event listener when the component that uses this hook is unmounted.</p> <p>In the end we are exporting our hook for it to be accessible where we want to use it.</p> <h3> Implementing the Hook </h3> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>import { useRef, useState } from "react"; import "./styles.css"; import useOutsideClick from "./useOutsideClick"; export default function App() { const ref = useRef&lt;any&gt;(null); const [visible, setVisible] = useState(false); useOutsideClick(ref, setVisible); return ( &lt;&gt; &lt;button ref={ref} onClick={() =&gt; setVisible(true)} className="drop-down"&gt; This is a drop down &lt;/button&gt; {visible ? ( &lt;ul&gt; &lt;li&gt;Item 1 &lt;/li&gt; &lt;li&gt;Item 2 &lt;/li&gt; &lt;li&gt;Item 3 &lt;/li&gt; &lt;li&gt;Item 4 &lt;/li&gt; &lt;/ul&gt; ) : null} &lt;/&gt; ); } </code></pre> </div> <p>In this code, we are utilizing our custom hook to hide the list element when the click happens outside of the button component.</p> <p><strong>useRef:</strong> A react built-in Hook to create a reference for the specified element. In our case, we are using it to create a reference for the <strong>button</strong> element. Which latter on we will pass to our custom hook as a first argument.</p> <p><strong>visible:</strong> we have declared a state variable named <strong>visible</strong> which we are using to display our list conditionally. If it is false the list will not be visible and if it's set to true, the list will be rendered.</p> <p><strong>useOutsideClick:</strong> First we are importing our cusotm hook from the file name <code>useOutsideClick</code>. Then we are passing two arguments to it. The first one is the reference to the element we want to track click for. and the second is the callback which is going to be triggered once the click occurs outside of the button.</p> <h3> Conclusion </h3> <p>Hooks in React allow developers to add stateful logic to the functional component, providing them with the same capabilities as the class component. The introduction of custom hooks has further extended the possibilities, As developer can build their own hooks and reuse the stateful logic between different components.</p> javascript react hooks webdev Integrating Hashnode Blogs into Your React App with the Hashnode API Hamza Ali Wed, 01 Feb 2023 19:33:51 +0000 https://dev.to/hat52/integrating-hashnode-blogs-into-your-react-app-with-the-hashnode-api-4o4g https://dev.to/hat52/integrating-hashnode-blogs-into-your-react-app-with-the-hashnode-api-4o4g <p>If you have a portfolio website and you also do blogging then it is only just fair to have representation of your blogs on your website. Same reason for me to integrate Hasnode blogs on my portfolio website. I am currently building my <a href="proxy.php?url=http://hamzaa.dev/" rel="noopener noreferrer">portfolio</a> website and I have a blog section in it. I was looking for a way I could easily set up my blogs on my portfolio.</p> <p>The problem that I had was I didn't know how I should approach it. Initially, I was thinking of building my own layout for the blog section and placing all the blogs in my source code. But then after spending some time on the internet and looking for the easy way. I finally found a way that let me integrate my Hashnode blog into my portfolio.</p> <h2> Hashnode API </h2> <p>Hashnode has a GraphQL api that exposes Hashnode blogs to the user. In the below attachment, you can see that I have fetched data for the user name <strong><em>hat52</em></strong> which is my account.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>const GET_USER_BLOGS = ` query GetUserArticles($page: Int!) { user(username: "hat52") { publication { posts(page: $page) { title brief slug dateAdded coverImage contentMarkdown } } } } `; </code></pre> </div> <p><em>GraphQL query to fetch data</em></p> <p>I am fetching the following data for every blog post that I have posted on Hashnode.</p> <ul> <li> <strong>brief: A brie</strong>f description of the blog</li> <li> <strong>title:</strong> Title of the blog</li> <li> <strong>slug:</strong> A slug is the part of a URL that identifies a particular article on your blog and explains the page's content</li> <li> <strong>dateAdded:</strong> Date when I posted the blog on Hashnode</li> <li> <strong>coverImage:</strong> Cover image of the blog post</li> <li> <strong>contentMarkdown:</strong> Get the content represented in markdown</li> </ul> <p>Similarly, you can fetch other information about the blog. You can check the Hashnode <a href="proxy.php?url=https://api.hashnode.com/" rel="noopener noreferrer">API Playground</a> to further explore the field that this API allows you to fetch. It allows you to build and try out your request first, and it has detailed documentation of the models available.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1675230940833%2Fa434f62a-0a52-4397-9047-d38a9a9795e8.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1675230940833%2Fa434f62a-0a52-4397-9047-d38a9a9795e8.png" alt="https://cdn.hashnode.com/res/hashnode/image/upload/v1675230940833/a434f62a-0a52-4397-9047-d38a9a9795e8.png"></a></p> <h2> Advantages of using Hashnode API </h2> <ul> <li> <strong>Quick setup</strong>: Easily add a blog section to your portfolio website with the Hashnode API.</li> <li> <strong>Powerful tools</strong>: Create rich, engaging content with Hashnode's text formatting, image, and code blocks.</li> <li> <strong>Can handle traffic</strong>: With Hashnode's scalable infrastructure, your blog section can handle a large volume of readers.</li> <li> <strong>Safe and secure</strong>: Your content is protected with Hashnode's security measures, keeping your blog section safe from cyber-attacks.</li> <li> <strong>Customizable design</strong>: Personalize your blog section with custom branding, styles, and functionality.</li> <li> <strong>Track success</strong>: Use Hashnode's analytics to see how your blog is performing and make informed content decisions.</li> </ul> <h2> Fetching Data </h2> <p>I have used the JavaScript fetch method to fetch the data from Hashnode. After fetching that data I will map the response to an interface I defined.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>export const fetchBlogs = async () =&gt; { let allBlogsFetched = false; let page = 0; const articles = []; while (!allBlogsFetched) { let response = await gql(GET_USER_BLOGS, { page: page }); articles.push(...response.data.user.publication.posts); if (response.data.user.publication.posts.length === 0) { allBlogsFetched = true; } page++; } return articles; }; async function gql(query: string, variables = {}) { const data = await fetch('https://api.hashnode.com/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query, variables }) }); return data.json(); } </code></pre> </div> <h2> Displaying the content </h2> <p>I am going to use hooks rather than the class component of React. To fetch the data from an API we need to call the API in useEffect. I Will use useState to manage the data fetched from API and to display it on the interface.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>const [blogs, setBlogs] = useState&lt;any&gt;([]); useEffect(() =&gt; { const getBlogs = async () =&gt; { const response = await fetchBlogs(); setBlogs(response); }; getBlogs(); }, []); </code></pre> </div> <p>Now After fetching the data I need to display it on the screen. For that I will use <strong>Array.prototype.map</strong> to iterate over the blogs array.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>{blogs.map((data: any) =&gt; { return &lt;BlogCard data={data} /&gt;; })} </code></pre> </div> <p>In the above code snippet, I am returning the <strong>BlogCard</strong> component for every entry in the array and I am also passing the data object to the component.</p> <p>Here is the card component that will display the blog. I have used tailwind CSS for styling the card component.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>import { getDayMonth } from '@/utils'; export default function BlogCard({ data }: any) { const date = getDayMonth(data.dateAdded); return ( &lt;div className="rounded-[12px] h-max flex flex-col items-start gap-4 w-[80%] cursor-pointer"&gt; &lt;div className="rounded-[12px] relative header md:h-[300px] w-full overflow-hidden "&gt; &lt;img src={data.coverImage} alt="a" className="rounded-[12px] h-full w-full hover:scale-110 object-fit transition-all duration-500 ease-in-out transform " /&gt; &lt;p className="date flex flex-col items-center w-[40px] h-[50px] absolute right-4 top-10 p-1 rounded-[4px] text-white bg-cyanBlue"&gt; &lt;span&gt;{date.day}&lt;/span&gt; &lt;span&gt;{date.month}&lt;/span&gt; &lt;/p&gt; &lt;/div&gt; &lt;h5 className="uppercase hover:text-cyanBlue hover:scale-90 transition-all duration-500 hover:-translate-x-6 overflow-hidden truncate w-full text-white font-semibold "&gt; {data.title} &lt;/h5&gt; &lt;p className="text-white overflow-hidden truncate w-full"&gt;{data.brief}&lt;/p&gt; &lt;button className="bg-cyanBlue px-4 py-2 text-white rounded-[50px]"&gt;Read More&lt;/button&gt; &lt;/div&gt; ); } </code></pre> </div> <h2> Result </h2> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1675277361459%2F78ba425c-2d40-4a04-89d7-dce04af1fc63.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1675277361459%2F78ba425c-2d40-4a04-89d7-dce04af1fc63.png" alt="https://cdn.hashnode.com/res/hashnode/image/upload/v1675277361459/78ba425c-2d40-4a04-89d7-dce04af1fc63.png"></a></p> <h2> Conclusion </h2> <p>If you have your portfolio website and you also write blogs then you must have your blog on your portfolio. It increases the user interactivity on your website and also you have another section to show the world.</p> <p>Above I have explained one of the many ways to integrate blogs into your project. I have explained how we can use GraphQL to fetch data from Hashnode API. Then we looked into how we can call an API with the help of useEffect and how we can store data by using useState hook. After storing the data we needed to Iterate over it to display it on our interface for that we used Array.prototype.map.</p> <p>Visit the finished site at <strong><a href="proxy.php?url=http://hamzaa.dev/" rel="noopener noreferrer">hamzaa.dev</a></strong> (The site is in progress but you can visit the blog section which is complete).</p> <p>If you have any suggestions please leave them in the comments.</p> typescript tailwindcss webdev react Connecting your Vercel app to a GoDaddy Domain: A Step-by-Step Guide Hamza Ali Fri, 20 Jan 2023 21:03:35 +0000 https://dev.to/hat52/connecting-your-vercel-app-to-a-godaddy-domain-a-step-by-step-guide-11lc https://dev.to/hat52/connecting-your-vercel-app-to-a-godaddy-domain-a-step-by-step-guide-11lc <p>Deploying your app on Vercel is a straightforward process, and the platform has great documentation to guide you through configuring a custom domain. However, if you are not familiar with GoDaddy, connecting your deployed app to a GoDaddy domain can be a bit challenging. In this blog post, I will walk you through the steps of connecting your Vercel app to a GoDaddy domain, making the process easy and painless.</p> <ul> <li><strong>Deploying your app on Vercel</strong></li> </ul> <p>If you don't have an account on vercel then signup for a free account. After signing up go to overview and click on Add New the button you then click on the project then connect your GitHub repo that you want to deploy on vercel and give it a name that you want after that vercel will handle everything for you. Vercel by default gives you a domain name related to the project that you finished deploying.</p> <ul> <li>After creating and deploying your project click on it. It will take you to the detail page of the project. Then click on the View Domain button.</li> </ul> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F83haw4skd396gkwkj34p.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F83haw4skd396gkwkj34p.png" alt="vercel project" width="800" height="160"></a></p> <ul> <li>Add the domain that you have already purchased from Godaddy. </li> </ul> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnkogabmbcdn1k4lb9dsv.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnkogabmbcdn1k4lb9dsv.png" alt="Domains" width="800" height="253"></a></p> <ul> <li>After you add the domain you are given this Invalid Configuration message and given the option to either configure your domain by A record or Nameservers (A Record method recommended). Choose which method you would like to configure your domain.</li> </ul> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyzohmeq7by03j8sqjg0h.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyzohmeq7by03j8sqjg0h.png" alt="Invalid configuration" width="800" height="354"></a></p> <ul> <li>Go to your GoDaddy account and navigate to the Domain portfolio. </li> </ul> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxjhycinv060d7fu1h4rr.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxjhycinv060d7fu1h4rr.png" alt="godaddy portfolio" width="800" height="372"></a></p> <ul> <li>Click on the lock icon in the third column. Enter the verification code in the field that you should have received from Godaddy. What this step will do is it will unlock your domain and make it available to connect to other platforms in our case Vercel.</li> </ul> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwc9wevyg9mtb5jygkand.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwc9wevyg9mtb5jygkand.png" alt="unlock domains" width="800" height="523"></a></p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft5r9tb73mcjhw7hawpcj.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft5r9tb73mcjhw7hawpcj.png" alt="verify identity" width="800" height="578"></a></p> <ul> <li>The next step is to click on the three-dot icon in the fourth column which will open a menu. The options that we are concerned about are Edit DNS and Edit nameservers . We can use either one of these to configure our domain. I will walk you through both. </li> </ul> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2xw6yca1htfmksobs069.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2xw6yca1htfmksobs069.png" alt="menu" width="800" height="499"></a></p> <p><strong>Edit DNS</strong></p> <p>After clicking on the Edit DNS option you will be taken to the DNS Management page. You should be able to see different types of entries in the DNS Records table . We need to add the Vercel record info in this table.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvmflvr6b8g99p42k0dr5.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvmflvr6b8g99p42k0dr5.png" alt="Edit DNS" width="800" height="454"></a><br> After adding the record you might be prompted on vertical to remove an existing A record, which you should do.</p> <p><strong>Nameservers</strong></p> <p>You are provided the Vercel nameservers that you can use in GoDaddy.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg43o0ui5spsqm1jqt3yn.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg43o0ui5spsqm1jqt3yn.png" alt="Nameservers" width="800" height="210"></a></p> <p>Now you need to replace Godaddy nameservers with vercel nameservers and then Godaddy will send you an email to verify your action. After you verify these changes will reflect.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbpotpkixl209sxmhqky5.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbpotpkixl209sxmhqky5.png" alt="edit nameservers" width="747" height="511"></a></p> <ul> <li>Once the configuration is set up correctly, you will no longer see the invalid message instead, you will see Valid Configuration and the redirect to your domain. </li> </ul> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6qmoa74b152p5vmhxz63.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6qmoa74b152p5vmhxz63.png" alt="result" width="800" height="138"></a></p> <p>In conclusion, connecting your Vercel app to a GoDaddy domain can be a bit challenging, but with this guide, I hope you found the process easy and painless. By following the steps outlined in this blog post, you will be able to successfully connect your Vercel app to your GoDaddy domain, and enjoy the benefits of using Vercel as your app's hosting platform. Happy deploying!</p> devops deploying vercel tutorial Creating and Downloading a CSV File Using Pure JavaScript - A Step by Step Guide Hamza Ali Sat, 14 Jan 2023 19:53:35 +0000 https://dev.to/hat52/creating-and-downloading-a-csv-file-using-pure-javascript-a-step-by-step-guide-4ogg https://dev.to/hat52/creating-and-downloading-a-csv-file-using-pure-javascript-a-step-by-step-guide-4ogg <p>CSV files are an essential part of computer programming. There might some cases when there is some data and you want the user to be able to download it. In that case, CSV file helps the programmer to use them to download data from the browser.</p> <p>Cav files are simple to store data in the form of tables. It also doesn’t need any extra library to make the download possible. You can use plain JavaScript to implement this functionality in your App. You can open the CSV file in MS Excel and see the data present inside it. Almost every database requires CSV files to back up the data. so without any further ado let's get into it.</p> <p>If you prefer to see the code in action, check out this <a href="proxy.php?url=https://youtu.be/M6Sc2yo4gSw" rel="noopener noreferrer">video tutorial</a>.</p> <h2> why do we need CSV files? </h2> <p>CSV files store data in a table format that is easy to understand.</p> <p>They are simple and easy to use for programmers.</p> <p>Many programmers prefer to use CSV files to download data from a website.</p> <p>CSV files do not require any third-party libraries to create and download.</p> <p>You can easily use a CSV file on your website using simple JavaScript methods and commands.</p> <h2> How to Download CSV file? </h2> <p>To download data in the form of a CSV file your data should be represented in a multi-dimensional array like the below code.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>var csvFileData = [ ['Alan Walker', 'Singer'], ['Cristiano Ronaldo', 'Footballer'], ['Saina Nehwal', 'Badminton Player'], ['Arijit Singh', 'Singer'], ['Terence Lewis', 'Dancer'] ]; </code></pre> </div> <h2> Implementation </h2> <p>For this example, I am going to create my data instead of getting the actual data from the web page. For learning purposes, you can follow this blog as it is but if you are here to implement this feature with real data then you only need to replace the csvFileData with your actual data.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>&lt;html&gt; &lt;head&gt; &lt;title&gt; Download CSV file &lt;/title&gt; &lt;/head&gt; &lt;script&gt; //create CSV file data in an array var csvFileData = [ ['Alan Walker', 'Singer'], ['Cristiano Ronaldo', 'Footballer'], ['Saina Nehwal', 'Badminton Player'], ['Arijit Singh', 'Singer'], ['Terence Lewis', 'Dancer'] ]; //create a user-defined function to download CSV file function csvDownload() { //define the heading for each row of the data var csv = 'Name,Profession\\n'; //merge the data with CSV csvFileData.forEach(function(row) { csv += row.join(','); csv += "\\n"; }); var hiddenElement = document.createElement('a'); hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv); hiddenElement.target = '_blank'; //provide the name for the CSV file to be downloaded hiddenElement.download = 'Famous Personalities.csv'; hiddenElement.click(); } &lt;/script&gt; &lt;body&gt; &lt;h3&gt; Click the button to download the CSV file &lt;/h3&gt; &lt;!-- create an HTML button to download the CSV file on click --&gt; &lt;button onclick="cavDownload()"&gt; Download CSV &lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> </div> <h2> Explanation </h2> <p>This code creates a webpage with a button labeled "Download CSV". When the button is clicked, a CSV file is created and downloaded to the user's device. The file contains a table of data with two columns, "Name" and "Profession," and five rows of data for various famous personalities.</p> <p>The code first declares an array, "csvFileData," which holds the data for the table in nested arrays. Each inner array represents a row in the table, with the first element being the name and the second element being the profession.</p> <p>The button's "onclick" attribute calls the function "csvDownload" when clicked. This function creates a string variable "csv" with the first row of the table as the header "Name, Profession". Then it iterates over the data in csvFileData, concatenating each row of data to the "csv" variable, separated by commas and newline characters.</p> <p>The function then creates a hidden HTML "a" element, which is used to create a link for the CSV file. The link's "href" attribute is set to the "csv" variable, with the "data:text/csv;charset=utf-8," prefix and encoded using the "encodeURI" function. The "target" attribute is set to "_blank" so that the CSV file will open in a new tab/window when clicked. The "download" attribute is set to "Famous Personalities.csv" so that the downloaded file will have this name. Finally, the function triggers the click event on the hidden element, triggering the download of the file.</p> <h2> Conclusion </h2> <p>In this blog post, we have discussed the importance of CSV files in computer programming, and how they can be used to download data from a website. We have also discussed how to create and download a CSV file using plain JavaScript without the need for any third-party libraries. We walked through a code example that demonstrates how to create a webpage with a button that, when clicked, creates and downloads a CSV file with a table of data for famous personalities. It also shows how easy it is to create a CSV file using JavaScript and how it can be used to store data in a table format. This makes it easy for programmers to use and understand and is also very useful in many applications.</p> automation data discuss Embedding YouTube Videos in HTML: A Step-by-Step Guide Hamza Ali Wed, 11 Jan 2023 19:15:26 +0000 https://dev.to/hat52/embedding-youtube-videos-in-html-a-step-by-step-guide-2946 https://dev.to/hat52/embedding-youtube-videos-in-html-a-step-by-step-guide-2946 <p>Hello everyone, welcome to my latest blog post. Today, I want to talk about a topic that I am sure many of you frontend developers out there can relate to - embedding a YouTube video in your project. Whether you're working on a personal website or a side project, you've likely come across the need to add a video to your page at some point. However, the process of embedding a video from YouTube in HTML can sometimes be a bit tricky. In this post, I will be sharing with you the steps I take when embedding a YouTube video in HTML and also some best practices that I have found to make the process as smooth as possible. So, without further ado, let's get started!</p> <p>For those who prefer to learn by watching, check out this <a href="proxy.php?url=https://youtu.be/ZkmCP3NIIvI" rel="noopener noreferrer">tutorial video</a></p> <p>First of all start with selecting a video from youtube that you want to embed. In my case, I selected a video from my channel in which I describe how we can use <a href="proxy.php?url=https://www.youtube.com/watch?v=a7cKMWsgGEM&amp;t=3s" rel="noopener noreferrer">meta tags in react</a>.</p> <p>After selecting a video click on the share button on that video and then a pop-up will open in which you will have different options.</p> <p><a href="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1673460831004%2F5f102753-883c-41a7-b1c7-39ec77913c81.png%2520align%3D" class="article-body-image-wrapper"><img src="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1673460831004%2F5f102753-883c-41a7-b1c7-39ec77913c81.png%2520align%3D" width="800" height="400"></a></p> <p>Select embed and copy that code and paste it into your project.</p> <p><a href="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1673460794953%2Feadacb86-fbb5-4672-b449-7e6c2c2a1746.png%2520align%3D" class="article-body-image-wrapper"><img src="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1673460794953%2Feadacb86-fbb5-4672-b449-7e6c2c2a1746.png%2520align%3D" width="800" height="400"></a></p> <p>In my case, I have created a new project in which I am going to embed this video. Here is the code snippet of it.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight xml"><code><span class="cp">&lt;!DOCTYPE html&gt;</span> <span class="nt">&lt;html</span> <span class="na">lang=</span><span class="s">"en"</span><span class="nt">&gt;</span> <span class="nt">&lt;head&gt;</span> <span class="nt">&lt;meta</span> <span class="na">charset=</span><span class="s">"UTF-8"</span> <span class="nt">/&gt;</span> <span class="nt">&lt;meta</span> <span class="na">name=</span><span class="s">"viewport"</span> <span class="na">content=</span><span class="s">"width=device-width, initial-scale=1.0"</span> <span class="nt">/&gt;</span> <span class="nt">&lt;meta</span> <span class="na">http-equiv=</span><span class="s">"X-UA-Compatible"</span> <span class="na">content=</span><span class="s">"ie=edge"</span> <span class="nt">/&gt;</span> <span class="nt">&lt;title&gt;</span>Embed youtube video in HTML<span class="nt">&lt;/title&gt;</span> <span class="nt">&lt;link</span> <span class="na">rel=</span><span class="s">"stylesheet"</span> <span class="na">href=</span><span class="s">"index.css"</span> <span class="nt">/&gt;</span> <span class="nt">&lt;/head&gt;</span> <span class="nt">&lt;body&gt;</span> <span class="nt">&lt;iframe</span> <span class="na">width=</span><span class="s">"560"</span> <span class="na">height=</span><span class="s">"315"</span> <span class="na">src=</span><span class="s">"https://www.youtube.com/embed/a7cKMWsgGEM"</span> <span class="na">title=</span><span class="s">"YouTube video player"</span> <span class="na">allow=</span><span class="s">"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"</span> <span class="err">allowfullscreen</span> <span class="nt">&gt;&lt;/iframe&gt;</span> <span class="nt">&lt;/body&gt;</span> <span class="nt">&lt;/html&gt;</span> </code></pre> </div> <ul> <li><p>allowfullscreen: Set to <code>true</code> if the <code>&lt;iframe&gt;</code> can activate fullscreen mode by calling the <a href="proxy.php?url=https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen" rel="noopener noreferrer"><code>requestFullscreen()</code></a> method</p></li> <li><p>allow: Specifies a <a href="proxy.php?url=https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy" rel="noopener noreferrer">Permissions Policy</a> for the <code>&lt;iframe&gt;</code>. The policy defines what features are available to the <code>&lt;iframe&gt;</code> (for example, access to the microphone, camera, battery, web-share, etc.) based on the origin of the request.</p></li> <li><p>title: The <code>title</code> the global attribute contains text representing advisory information related to the element it belongs to.</p></li> <li><p>src: Adding a Link to the Desired Video for Embedding.</p></li> <li><p>height and width: Specify the Size.</p></li> </ul> <p>You can keep the attribute as they are but if you want to style them you can do it by giving the <code>class</code> attributed to the iframe tag.</p> <p><strong>Here is my final code and its result</strong><br> </p> <div class="highlight js-code-highlight"> <pre class="highlight xml"><code><span class="nt">&lt;iframe</span> <span class="na">width=</span><span class="s">"600px"</span> <span class="na">height=</span><span class="s">"300px"</span> <span class="na">src=</span><span class="s">"https://www.youtube.com/embed/a7cKMWsgGEM"</span> <span class="na">title=</span><span class="s">"YouTube video player"</span> <span class="na">allow=</span><span class="s">"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"</span> <span class="err">allowfullscreen</span> <span class="nt">&gt;&lt;/iframe&gt;</span> </code></pre> </div> <p><a href="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1673462950997%2F5b9e3666-ffaa-4c67-b32a-484b4ac08023.png%2520align%3D" class="article-body-image-wrapper"><img src="proxy.php?url=https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1673462950997%2F5b9e3666-ffaa-4c67-b32a-484b4ac08023.png%2520align%3D" width="800" height="400"></a></p> <p>Embedding YouTube videos in HTML is a simple process that allows you to share rich content with your audience. I hope this guide has helped get you started. Happy embedding!</p> watercooler Use multiple GitHub accounts on same system Hamza Ali Wed, 14 Dec 2022 18:36:10 +0000 https://dev.to/hat52/use-multiple-github-accounts-on-same-system-cf7 https://dev.to/hat52/use-multiple-github-accounts-on-same-system-cf7 <p>I was working with two different GitHub accounts one is my personal account and the other is my work account. I had these two accounts set up on different systems but recently my personal system had some connectivity issues so I had to use both of my GitHub accounts on my work system. I did some research on how I can achieve that. In this blog post, I will try to explain how we can solve the problem of using two GitHub accounts on the same machine.</p> <h2> <strong>Secure Shell Protocol(SSH)</strong> </h2> <p>To use two different GitHub accounts on the same machine we are going to use ssh.</p> <p>💡 SSH or Secure Shell is a network communication protocol that enables two computers to communicate and share data. An inherent feature of ssh is that the communication between the two computers is encrypted meaning that it is suitable for use on insecure networks. You can read more about ssh <a href="proxy.php?url=https://www.ucl.ac.uk/isd/what-ssh-and-how-do-i-use-it#:~:text=SSH%20or%20Secure%20Shell%20is,web%20pages" rel="noopener noreferrer">here</a></p> <h2> Let’s Get Into It. </h2> <ul> <li> <p><strong>Create SSH Key</strong></p> <p>We will need to create an ssh key for all the accounts that we are going to use on the machine.</p> <p>To do that open the terminal and move into the ssh directory</p> 💡 `$ cd ~/.ssh` <p>Now we need to generate an ssh key. The syntax for the generation of an ssh key is</p> 💡 `ssh-keygen -t rsa -C "email-address" -f "github-username"` <ul> <li>-C option stands for comment which helps identify the ssh key</li> <li>-f option stands for file name which means that whatever name you pass after -f that name will be the name of our ssh key file inside the ssh directory.</li> </ul> <p>After understanding how we can create the ssh key let’s now create the ssh key for our two accounts</p> <p><strong><em>Personal Account</em></strong></p> <p>💡 <code>ssh-keygen -t rsa -C "[email protected]" -f "personal"</code></p> <p><strong><em>Work Account</em></strong></p> <p>💡 <code>ssh-keygen -t rsa -C "[email protected]" -f "work"</code></p> <p>After entering the command the terminal will ask for a passphrase, leave it empty and proceed.</p> <p>What this command will do is it will create two files one with <code>.pub</code> extension and one without any extension. In our case four files will be created in the ssh directory named <code>personal</code> , <a href="proxy.php?url=http://personal.pub" rel="noopener noreferrer">`p</a>ersonal.pub<code> , </code>work<code> and </code>work.pub`</p> </li> <li><p><strong>Add SSH keys to SSH Agent</strong></p></li> </ul> <p>Our keys will not work until we add them in ssh-agent or they will ask for a paraphrase every time we the key. You can read more about it <a href="proxy.php?url=https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent" rel="noopener noreferrer">here</a>.</p> <p>let's add both of our key to ssh-agent</p> <p>💡 ssh-add -K ~/.ssh/work<br> ssh-add -K ~/.ssh/personal</p> <ul> <li><strong>Add SSH key to GitHub</strong></li> </ul> <p>Now to use these newly generated ssh keys we need to add them in our GitHub account. So the work key will go into our work GitHub account similarly our personal key will go into our Personal GitHub account.</p> <ul> <li>Now copy the key form the <code>.pub</code> extension file.</li> <li>Sign in to GitHub Account</li> <li>Goto <strong>Settings</strong> &gt; <strong>SSH and GPG keys</strong> &gt; <strong>New SSH Key</strong> </li> <li>Paste your copied public key and give it a Title of your choice.</li> </ul> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9wck9ym16zsr75762xe3.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9wck9ym16zsr75762xe3.png" alt="sshshot"></a></p> <ul> <li> <p><strong>Create a Config File and Make Host Entries</strong></p> <p>After adding the key to our GitHub account we need to create a config file in the .ssh directory and make the host entry.</p> <p>If the config file is not already created, create a new config file and paste the following data into it.<br> </p> <pre class="highlight plaintext"><code># githubPersonal Host personal github.com HostName github.com PreferredAuthentications publickey IdentityFile ~/.ssh/personal # githubWork Host work github.com HostName github.com PreferredAuthentications publickey IdentityFile ~/.ssh/work </code></pre> <p>Now everything is done the only thing that remains is to clone the repositories. To achieve that, copy the ssh URL of the repository that you want to clone and use the below command</p> 💡 `git clone git@{your-username}:{owner-user-name}/{the-repo-name}.git` <p>if I want to copy a repo from my personal account the above command will look something like this</p> 💡 `git clone git@personal:Hat52/blood-donation.git` <p>From now on, to ensure that our commits and pushes from each repository on the system use the correct GitHub user — we will have to configure <strong>user.email</strong> and <strong>user.name</strong> in every repository freshly cloned or existing before.</p> <p>To do this use the following commands.<br> </p> <pre class="highlight plaintext"><code> git config user.email "[email protected]" git config user.name "Hamza Ali" git config user.email "[email protected]" git config user.name "Hamza Ali" </code></pre> <p>Pick the correct pair for your repository accordingly.</p> <p>To push or pull to the correct account we need to add the remote origin to the project<br> </p> <pre class="highlight plaintext"><code> git remote add origin git@personal:{personal-username}/{personal-repo} git remote add origin git@work:{user-name}/{work-repo} </code></pre> <p>Now you can use:<br> </p> <pre class="highlight plaintext"><code> git push git pull </code></pre> <p><strong><code>This approach can be used for more then two account.</code></strong></p> </li> </ul> <p>That is it from this post if you have any question or suggestion please leave them in the comments.</p> git github beginners webdev IIFE(immediately-Invoked function Expression) Hamza Ali Sun, 04 Dec 2022 19:54:23 +0000 https://dev.to/hat52/iifeimmediately-invoked-function-expression-a9p https://dev.to/hat52/iifeimmediately-invoked-function-expression-a9p <ul> <li><p>The term immediately-Invoked function Expression was tossed by <a href="proxy.php?url=%5Bhttps://web.archive.org/web/20171201033208/http://benalman.com/news/2010/11/immediately-invoked-function-expression/#iife%5D(https://web.archive.org/web/20171201033208/http://benalman.com/news/2010/11/immediately-invoked-function-expression/#iife)">BEN ALMAN</a> in his blog. Before that it was referred to as self-executing anonymous function. As the name suggests it is a kind of JavaScript function which gets executed immediately after its declaration.</p></li> <li><p>A normal JavaScript function can be declared by one of these methods<br> </p></li> </ul> <div class="highlight js-code-highlight"> <pre class="highlight jsx"><code><span class="c1">//First method</span> <span class="kd">function</span> <span class="nx">foo</span><span class="p">(){</span> <span class="c1">//code }</span> <span class="c1">//second method </span> <span class="kd">const</span> <span class="nx">foo</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(){</span><span class="c1">//code}</span> <span class="c1">//both of these functon can be invoked by putting the pranthesis after their name</span> <span class="nx">foo</span><span class="p">()</span> <span class="c1">// This will invoke the function and will cause its execution</span> </code></pre> </div> <p>But what if we want to invoke a function right after its declaration? JavaScript doesn't allow putting parenthesis after a function declaration<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight jsx"><code><span class="kd">function</span> <span class="nx">foo</span><span class="p">(){</span><span class="c1">//code}()</span> <span class="c1">// This will throw syntex error same goes for the other mehtod</span> <span class="kd">const</span> <span class="nx">foo</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(){</span><span class="c1">//code}()</span> <span class="c1">//But if we pass argument to the paranthesis after the function declaration no exception will occuer</span> <span class="kd">function</span> <span class="nx">foo</span><span class="p">(){</span><span class="c1">//code}(0)</span> <span class="c1">// This will not throw any exception because JavaScript treets this piece of code in different way</span> <span class="kd">function</span> <span class="nx">foo</span><span class="p">(){</span><span class="c1">//code}</span> <span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="c1">//This is how JavaScript treets this piece of code.</span> </code></pre> </div> <p>So we know that JavaScript doesn’t throw errors when we pass some argument to the parenthesis. So to create an IIFE we will pass our function as an argument to the parenthesis and after the parenthesis, we will add another parenthesis to invoke the function that we just passed.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight jsx"><code><span class="p">(</span><span class="kd">function</span><span class="p">(){</span><span class="c1">//code})()</span> </code></pre> </div> <h2> Use cases </h2> <ul> <li> <strong>Avoid polluting namespace</strong> </li> </ul> <p>As our application gets big the need of we want to avoid duplicating the names of our variables to avoid confusion. In case when we know that a piece of code will only execute once we can use IIFE.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight jsx"><code><span class="p">(</span><span class="kd">function</span><span class="p">(){</span> <span class="c1">//code</span> <span class="kd">let</span> <span class="nx">veriable1</span> <span class="kd">let</span> <span class="nx">veriable2</span> <span class="c1">//code</span> <span class="p">})()</span> <span class="c1">//As soon as this IIFE gets executed the veriable1 and veriable2 will be discarded and will</span> <span class="c1">//be available to you later in the file</span> </code></pre> </div> <ul> <li> <strong>Privacy</strong> </li> </ul> <p>we can use <strong>IIFE</strong> to create private and public variables and methods.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight jsx"><code><span class="kd">const</span> <span class="nx">canYouSeeMe</span> <span class="o">=</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">(()</span> <span class="o">=&gt;</span> <span class="p">{</span> <span class="kd">let</span> <span class="nx">privateVariable</span> <span class="o">=</span> <span class="mi">5</span><span class="p">;</span> <span class="kd">function</span> <span class="nx">iamHidden</span><span class="p">()</span> <span class="p">{</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">haha YOU can't see me</span><span class="dl">"</span><span class="p">);</span> <span class="p">}</span> <span class="k">return</span> <span class="p">{</span> <span class="nx">youCanSeeMe</span><span class="p">()</span> <span class="p">{</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">'</span><span class="s1">you can see me</span><span class="dl">'</span><span class="p">);</span> <span class="p">}</span> <span class="p">};</span> <span class="p">})();</span> <span class="kd">const</span> <span class="nx">hideSeek</span> <span class="o">=</span> <span class="nx">canYouSeeMe</span><span class="p">();</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">hideSeek</span><span class="p">.</span><span class="nx">youCanSeeMe</span><span class="p">());</span> <span class="c1">// This will print out "you can see me"</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">hideSeek</span><span class="p">.</span><span class="nx">iamHidden</span><span class="p">());</span> <span class="c1">// undefined, because this method is private</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">hideSeek</span><span class="p">.</span><span class="nx">privateVariable</span><span class="p">);</span> <span class="c1">// undefined, because this veriable is private</span> </code></pre> </div> <ul> <li> <p><strong><em>Closure</em></strong></p> <p>Before the introduction of <strong>let</strong> and <strong>const</strong> in ES6 and block scope. With the var, we only have function and global scope.</p> <p>Let’s take a scenario<br> </p> <pre class="highlight jsx"><code><span class="kd">const</span> <span class="nx">buttons</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementsByClassName</span><span class="p">(</span><span class="dl">'</span><span class="s1">className</span><span class="dl">'</span><span class="p">);</span> <span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="nx">i</span><span class="o">&lt;</span><span class="mi">6</span><span class="p">;</span><span class="nx">i</span><span class="o">++</span><span class="p">){</span> <span class="nx">buttons</span><span class="p">[</span><span class="nx">i</span><span class="p">].</span><span class="nx">addEventListener</span><span class="p">(</span><span class="dl">'</span><span class="s1">click</span><span class="dl">'</span><span class="p">,</span><span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">){</span> <span class="nx">e</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">()</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">`I am button number </span><span class="p">${</span><span class="nx">i</span><span class="p">}</span><span class="s2">`</span><span class="p">)</span> <span class="p">})</span> <span class="p">}</span> <span class="c1">//what do you think the output of the button click will be.</span> <span class="c1">// If the button is clicked after the execution of the loop all of the six buttons</span> <span class="c1">// will print out "I am button number 6". Because at the end of the execution of the loop</span> <span class="c1">// the value of i is 6.</span> </code></pre> </li> </ul> <p>to encounter this before ES6 <strong>IIFE</strong> was used<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight jsx"><code><span class="kd">const</span> <span class="nx">buttons</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementsByClassName</span><span class="p">(</span><span class="dl">'</span><span class="s1">className</span><span class="dl">'</span><span class="p">);</span> <span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="mi">6</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span> <span class="p">((</span><span class="nx">index</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span> <span class="nx">buttons</span><span class="p">[</span><span class="nx">index</span><span class="p">].</span><span class="nx">addEventListener</span><span class="p">(</span><span class="dl">'</span><span class="s1">click</span><span class="dl">'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span> <span class="nx">e</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">`I am button number </span><span class="p">${</span><span class="nx">index</span><span class="p">}</span><span class="s2">`</span><span class="p">);</span> <span class="p">});</span> <span class="p">})(</span><span class="nx">i</span><span class="p">);</span> <span class="p">}</span> <span class="c1">// This execution will get you your desired result because of clouser</span> </code></pre> </div> <h3> That's it from this post </h3> <p>If you have any suggestions please leave them in the comments</p> javascript webdev beginners programming Add meta tag in react app Hamza Ali Fri, 25 Nov 2022 09:52:30 +0000 https://dev.to/hat52/add-meta-tag-in-react-app-526b https://dev.to/hat52/add-meta-tag-in-react-app-526b <h2> Background </h2> <p>I was searching for a open source project to contribute to on GitHub. So eventually I did found a project to contribute to.<br> Take a look a the <a href="proxy.php?url=https://github.com/Njong392/Abbreve" rel="noopener noreferrer">project</a>.</p> <p>When I found the project that looked like I could contribute to. I went on to reading the contribution document. After that I found an issue that did not had any assignee yet. So I got it assigned to me.</p> <p>The issue was to add meta tag in react application in a way that when we share the link of the project on social media. It should display a nice preview image and description about the project.<br> In this blog post I am going to show to how we can achieve that in react js.</p> <h2> What are META tags? </h2> <p>As <a href="proxy.php?url=https://www.w3schools.com/tags/tag_meta.asp" rel="noopener noreferrer">w3schools</a> document stats.</p> <ul> <li><p>The <code>Meta</code> tag defines metadata about an HTML document. Metadata is data (information) about data.</p></li> <li><p><code>Meta</code> tags always go inside the <code>Head</code> element</p></li> <li><p>Metadata will not be displayed on the page, but is machine parsable.</p></li> <li><p>Metadata is used by browsers (how to display content or reload page), search engines (keywords), and other web services.</p></li> </ul> <h2> Things we can achieve with meta tags </h2> <p>There are many thing that can be achieved by meta tags.</p> <ul> <li><p>Define key words for the search engine. Which help your site to be searchable when the user search for a specific keyword.<br> <code>&lt;meta name="keywords" content="HTML, CSS, JavaScript"&gt;</code></p></li> <li><p>Define description of your web page<br> <code>&lt;meta name="description" content="Meta tags usage blog"&gt;</code></p></li> <li><p>Define Author Name<br> <code>&lt;meta name="author" content="Hamza Ali"&gt;</code></p></li> <li><p>Setting the viewport to make your website look good on all devices<br> <code>&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;</code></p></li> </ul> <h2> What are Open Graph meta tags? </h2> <ul> <li><p>Open Graph meta tags are snippets of code that control how URLs are displayed when shared on social media. </p></li> <li><p>They’re part of Facebook’s Open Graph protocol and are also used by other social media sites, including LinkedIn and Twitter.</p></li> <li><p>You can find them in the <code>Head</code> section of a webpage. Any tags with og: before a property name are Open Graph tags<br> <code>&lt;meta property="og:title" content="Abbreve" /&gt;</code></p></li> </ul> <p>We will use open graph to show description when we share the link of our site on social media.</p> <h2> Lets get into </h2> <p>I will be assuming that you already have react project setup and in case you don't have a react app you can create it by running the command <code>npx create-react-app {NAME_OF_YOUR_APP}</code>.</p> <p>So to add the open graph meta tag we will need to edit the index.html file which is present in the public folder of react app. </p> <p>Navigate to index.html file and inside the head tag we are going to make changes. Remember META tags are always added in the head.</p> <p>To add a preview image we will add the following tag.</p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code> &lt;meta property="og:image" content="/src/assets/thumbnail.png" /&gt; </code></pre> </div> <p>In the above example we are setting the thumbnail.png as our preview image.</p> <p>Next we will set the description of our site.</p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code> &lt;meta name="description" content="This is a blog about usage of meta tags" /&gt; </code></pre> </div> <p>To add title of the site we will use </p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code> &lt;meta property="og:title" content="You site title" /&gt; </code></pre> </div> <p>For twitter we are going to use seperate meta tag which is</p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code> &lt;meta name="twitter:card" content="/src/assets/thumbnail.png" /&gt; </code></pre> </div> <p>This will set the image for the link share on Twitter.</p> <p>At the end your head tag should look like this</p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code> &lt;head&gt; &lt;meta charset="UTF-8" /&gt; &lt;link rel="icon" href="proxy.php?url=/favicon.ico" /&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt; &lt;meta property="og:title" content="Title" /&gt; &lt;meta property="og:image" content="/src/assets/thumbnail.png" /&gt; &lt;meta name="twitter:card" content="/src/assets/thumbnail.png" /&gt; &lt;meta name="description" content="Description" /&gt; &lt;title&gt;Title&lt;/title&gt; &lt;/head&gt; </code></pre> </div> <p>For testing our changes on localhost we are going to use this <a href="proxy.php?url=https://socialsharepreview.com/" rel="noopener noreferrer">Extension</a>.</p> <h2> Result </h2> <p>After the above implementation this is what you should get. Remember the content of meta tag should be set According to your need.</p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fctwuo8fuor1bqfadxi8t.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fctwuo8fuor1bqfadxi8t.png" alt="Eaxmple 1"></a></p> <p><a href="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9h9pkbgvd8vtvhdamejm.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9h9pkbgvd8vtvhdamejm.png" alt="Eaxmple 2"></a></p> <p>That it for this blog. If you have any queries or suggestion feel free to leave them in the comments.</p> javascript webdev programming react Open Source Contribution Hamza Ali Thu, 08 Sep 2022 19:42:06 +0000 https://dev.to/hat52/open-source-contribution-23n2 https://dev.to/hat52/open-source-contribution-23n2 <p>I have been into open source for quit a long time but I did not actively take any part in any open source project. Because for me finding a project to contribute was a hectic job . But for past couple of days I am trying to change that mentality of mine and in doing so I found a project that I was excited to contribute to. </p> <p>Check out the <a href="proxy.php?url=https://reactplay.io/">project</a>.</p> <p>When I found the project on github I went straight to the issue tab and found a issue that I felt I could contribute to. So I commented on it saying that assign this issue to me and lucky It got assigned to me .</p> <h4> A Little Twist in the tail </h4> <p>At first I thought it was a development issue but then after asking some question I found out that it was a designing job and the fun part is I don’t even know the A of web designing. I just know that we have a software called figma for creating the designs for web.</p> <p>I have been using figma to convert the design to html/CSS but never did I design any thing on figma. Luckily the job was not that tricky. So I watched some tutorial related to my use case and tried building a figma design. And after some work loaded hours I finally got the design ready to share for the issue. The design still have some improvements to do but I am really excited for the task. </p> <p>I will update you folks once I complete the design but if you want to take a look at the design right now you can go to this <a href="proxy.php?url=https://www.figma.com/file/LSSxDQEyFKIGczEiwe5pcS/Figma-design-for-hackathon-card?node-id=0%3A1">link</a>.</p> <p>This is what I love about open source. Before this issue I thought that I was incapable to design anything but now I am starting to feel like I can take up this job as well. When doing open source you are not bound to share the skill that you have already mastered but you can also learn new skills. </p> <p>I know building a single page design doesn’t make me a designer but its a start and you never know where you might end up once you take the first step.</p> <h4> Conclusion </h4> <p>I hope this article inspires you to get into the vast world of open source and contribute the evolution of the IT industry and in doing so enhance your skills as well.</p> opensource react javascript design How to create and publish npm package. Hamza Ali Sun, 04 Sep 2022 10:58:40 +0000 https://dev.to/hat52/how-to-create-and-publish-npm-package-53dc https://dev.to/hat52/how-to-create-and-publish-npm-package-53dc <h3> Creating npm package </h3> <p>Creating your npm package may sound difficult to do but it is surprisingly easy. In this blog post we are going to learn how we can create and publish npm package.</p> <p>Let’s create a folder named square-number you can name your folder whatever you want. Now inside square-number directory run the command npm init -y this will create a package.json file if you want to customize the values in pacakge.json then just run the command npm init and then answer the question that are asked after running the command.</p> <h4> Description of npm package </h4> <p>So for this bolg we are going to create a simple npm package which will only return us the square of a number and if a value other then number is passed, it will return a message saying “Invalid Number“. </p> <h4> Lets code </h4> <p>First we will create a index.js file inside our square-number folder. And inside that folder we are going to simply write a function which will satisfy what we described above.</p> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--UZEk0k0S--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/plt1udwikulnqvhi9i7s.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--UZEk0k0S--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/plt1udwikulnqvhi9i7s.png" alt="ss" width="377" height="76"></a><br> </p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>function square(number) { if(typeof number === 'number') { return number * number } return "Invalid Number" } </code></pre> </div> <p>The above function is going to be defined in our index.js file. What it does is it take a value and check if the value is of type number if it is then it returns the square of number otherwise if the value is not a number it returns a message saying “Invalid Number”.</p> <p>This is going to be a node module so we are going to export is from the index.js file by adding this below code at the bottom of our index file<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>module.exports = square </code></pre> </div> <p>Before publishing our package we will first need to test it locally for that we run the command <a href="proxy.php?url=https://docs.npmjs.com/cli/v8/commands/npm-link">npm link</a></p> <h4> Testing </h4> <p>To test our package we will create a new folder named test. And inside that folder we will test our package by passing the <strong><em>number, string and undefined</em></strong> to it.</p> <p>First run the command npm link square-number inside the test folder. What this will do is install the package inside test.</p> <p>After running the command you will notice that a node_modules folder is created in the test folder and inside that node_modules you will find our square-number.</p> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--8plIkyGK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rvuu08a63mqr93jxm6mf.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--8plIkyGK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rvuu08a63mqr93jxm6mf.png" alt="ss" width="371" height="130"></a></p> <p>Now to test we will create a index.js file and we will add the below code inside it.<br> </p> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>const squareNumber = require('square-number'); console.log(squareNumber(2)) console.log(squareNumber("2")) console.log(squareNumber(undefined)) </code></pre> </div> <p>At first line we are importing our package and next we are calling the package and passing it the number 2 and on the next line we are passing a string and then we are passing the value of undefined to test if all of our use cases are handled or not. Now lets run our index.js file by running the command node index.js .</p> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--SJ7E_D4E--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a5qinjgxnug8zayvp5sl.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--SJ7E_D4E--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a5qinjgxnug8zayvp5sl.png" alt="ss" width="610" height="77"></a></p> <p>You can see that the first call to our package return the square of number 2 and the second and third call returns a message saying “Invalid Number “ because we have passed a string and undefined to it.</p> <h4> Lets now publish our package </h4> <p>To publish we will first need to create <a href="proxy.php?url=https://www.npmjs.com/">npm</a> account. After creating the account we will sing in from our terminal by running the command <code>npm login</code> This will ask you to enter you account credentials. </p> <p>The next step is to run the command <code>npm publish</code> and this command will publish our package to npm server.</p> <p><a href="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--CGrumM3G--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7exio062pch3y44ks4ib.png" class="article-body-image-wrapper"><img src="proxy.php?url=https://res.cloudinary.com/practicaldev/image/fetch/s--CGrumM3G--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7exio062pch3y44ks4ib.png" alt="ss" width="880" height="427"></a></p> <h4> Note </h4> <blockquote> <p>Sometime the name of a package is already taken so to avoid that you might need to create a named space package by just altering the package.json file and change the name of package by adding a prefix to it which should have @ at the start of it <strong><em><a class="mentioned-user" href="proxy.php?url=https://dev.to/hat52">@hat52</a>/{name of the package}</em></strong> . To publish the named package you will need to run the command npm publish --access=public what this does is it make the package public because by default name space packages are private.</p> </blockquote> <h4> Conclusion </h4> <p>We have created a simple package which returns the square of the number passed to it. This is just to give context of how we can create a npm package. If you want to go into details of how we can create a complex package . Follow me because I am thinking of creating a time picker package in the near future.</p> <p>Thanks for reading and if you have any question or suggestion leave them in the comments.</p> javascript npm node programming Validating input field when it losses focus Hamza Ali Sun, 14 Aug 2022 12:41:13 +0000 https://dev.to/hat52/validating-input-field-when-it-losses-focus-2co4 https://dev.to/hat52/validating-input-field-when-it-losses-focus-2co4 <p>There are going to be several scenarios where you will have to call a function when the input field is set to inactive. May be you want to call an api or you want to validate a form field as soon as the input field is out of focus.</p> <h3> onblur </h3> <p>onblur function fires the moment input field is out of focus. This event is not cancelable and does not <a href="proxy.php?url=https://www.geeksforgeeks.org/event-bubbling-in-javascript/">bubble</a>. </p> <p>opposite of onblur is <a href="proxy.php?url=https://developer.mozilla.org/en-US/docs/Web/API/Element/focus_event"><strong>onfocus</strong></a>.</p> <h3> Let code to understand this better </h3> <div class="highlight js-code-highlight"> <pre class="highlight plaintext"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;title&gt;Validation of field on focs out&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="post" &gt; &lt;input type="text" placeholder="Email" id='email'&gt; &lt;span id='email-error'&gt;&lt;/span&gt; &lt;input type="password" placeholder="Password" id='password' &gt; &lt;span id='password-error'&gt;&lt;/span&gt; &lt;/form&gt; &lt;/body&gt; &lt;script&gt; const email =document.getElementById("email") const pasword =document.getElementById("password") pasword.addEventListener('blur',()=&gt;{ const error= document.getElementById('password-error') if(pasword.value?.length &lt; 8){ error.innerHTML = "password must be 8 or more characters" returnb } error.innerHTML = "" }) email.addEventListener('blur',()=&gt;{ const emailRegex = /^(([^&lt;&gt;()[\]\\.,;:\s@\"]+(\.[^&lt;&gt;()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ const error= document.getElementById('email-error') if(email.value.match(emailRegex)) { error.innerHTML = "" return } error.innerHTML = "invalid email" }) &lt;/script&gt; &lt;/html&gt; </code></pre> </div> <h3> Code explaination </h3> <p>we are validation both the password field and email field when they are set to inactive.</p> <p>In <strong>script</strong> tag we have attached blur event to both the field which mean as soon as the field go out of focus the second parameter of the <strong>addEventListner</strong> which is a function will be triggered.</p> <h4> Email validation </h4> <p>We are use regex to validate our email field. We are checking if the value of email field satisfies the regex if it does then we will remove the error from the error <strong>span</strong> and if the regex is not satisfied we will populate an error saying <strong>invalid email</strong></p> <h4> Password validation </h4> <p>For password validation we are check if the length of password is greater then or equal to 8 if it is then we will empty the error <strong>span</strong> of password and if it is not then we will display error saying <strong>password must be 8 or more characters</strong>.</p> <h3> Conclusion </h3> <p>You will face a lot of scenarios in your development career where you will have to validate a field or call a function when the field is set to inactive. I have tried to give you a some basic understanding of how you can achieve that . </p> <p>If you have any queries or suggestions leave them in comment. </p> <p>Thanks</p> webdev javascript beginners html