
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaScript Examples &#8211; CodeInDotNet</title>
	<atom:link href="https://www.codeindotnet.com/category/javascript-code-examples/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.codeindotnet.com</link>
	<description>C# Dot Net Programming tutorial &#38; code examples</description>
	<lastBuildDate>Tue, 02 Apr 2024 06:44:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>

<image>
	<url>https://www.codeindotnet.com/wp-content/uploads/2021/04/SiteIcon.png</url>
	<title>JavaScript Examples &#8211; CodeInDotNet</title>
	<link>https://www.codeindotnet.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to apply search filter for a list using Javascript</title>
		<link>https://www.codeindotnet.com/search-filter-div-list-items-javascript/</link>
					<comments>https://www.codeindotnet.com/search-filter-div-list-items-javascript/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 11 Dec 2023 14:56:37 +0000</pubDate>
				<category><![CDATA[JavaScript Examples]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=6565</guid>

					<description><![CDATA[Implement Filter/Search Functionality in Javascript When dealing with lists of items on a webpage, implementing a search filter can greatly enhance the user experience. In this tutorial, we&#8217;ll explore how to create a simple search filter using HTML, CSS, and JavaScript. Step 1: Set Up Your HTML Structure The syntax provided below creates the basic [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInHoriAd1"></div>
<script>
fetch('/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="446" height="284" src="https://www.codeindotnet.com/wp-content/uploads/2023/12/search-filter-list-items-javascript.jpg" alt="search filter list items javascript" class="wp-image-6625" srcset="https://www.codeindotnet.com/wp-content/uploads/2023/12/search-filter-list-items-javascript.jpg 446w, https://www.codeindotnet.com/wp-content/uploads/2023/12/search-filter-list-items-javascript-300x191.jpg 300w" sizes="(max-width: 446px) 100vw, 446px" /></figure>



<br>



<div class="wp-block-rank-math-toc-block toc-cust" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#step-1-set-up-your-html-structure">Step 1: Set Up Your HTML Structure</a></li><li><a href="#step-2-add-java-script-for-the-search-filter">Step 2: Add JavaScript for the Search Filter</a><ul><li><a href="#a-search-filter-list-items-by-exact-match-javascript-code">a) Search Filter List Items by Exact Match &#8211; Javascript Code</a></li><li><a href="#b-filter-search-list-items-by-multi-word-match-javascript-code">b) Filter Search List Items by Multi-Word Match &#8211; Javascript Code</a></li></ul></li><li><a href="#step-3-test-your-search-filter">Step 3: Test Your Search Filter</a><ul><li><a href="#test-1-exact-match-search-filter">Test 1 &#8211; Exact match search filter</a></li><li><a href="#test-2-multiple-search-filter-match-by-each-word">Test 2 &#8211; Multiple search filter match by each word</a></li></ul></li></ul></nav></div>



<br><br><br>



<h2 class="wp-block-heading h2Cust1" id="implement-filter-search-functionality-in-javascript"><strong>Implement Filter/Search Functionality in Javascript</strong></h2>



<br>



<p>When dealing with lists of items on a webpage, implementing a search filter can greatly enhance the user experience. In this tutorial, we&#8217;ll explore how to create a simple search filter using HTML, CSS, and JavaScript.</p>



<br>



<h2 class="wp-block-heading hLBRed" id="step-1-set-up-your-html-structure"><strong>Step 1: Set Up Your HTML Structure</strong></h2>



<br>



<p>The syntax provided below creates the basic HTML structure for a webpage. In this example, we&#8217;ll use an input field for the search query and an unordered list to display our items:</p>



<pre class="pchl"><code>&lt;html>
&lt;head>
	&lt;style>
		input&#91;type="text"]{
			background-color: #FFFFFF;
			border-style: solid;
			border-width: 1px;
			border-color: #cccccc;
			box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
			color: rgba(0, 0, 0, 0.75);
			height: 2.3125rem;
			margin: 0 0 1rem 0;
			padding: 0.5rem;
		}
		
		input&#91;type="text"]:focus{
			background: #fafafa;
			border-color: #999999;
			outline: none;
		}
		
		#myList{
			line-height: 1.6; 
			font-size: 18px; 
			overflow-y: scroll; 
			height: 500px; 
			border: 2px lightgray solid; 
			padding-left:15px;
		}
		
		#myInput{
			width: 80%; display:inline; border-radius: 10px;
		}
	&lt;/style>
&lt;/head>

&lt;body>
&lt;div>
	&lt;h2>&lt;strong>Filter Search List Using javascript&lt;/strong>&lt;/h2>
	&lt;br>
	&lt;div>
		&lt;!-- Search TextBox -->
		&lt;div>			
			&lt;span style="font-weight:bold; font-size: 18px; color: #555555; ">Search filter: &lt;/span>
			&lt;input type="text" id="myInput" placeholder=" type &amp;amp; filter..."/>
		&lt;/div>
		&lt;br>
		
		&lt;!-- Loading List of Items in each Div section -->
		&lt;div id="myList">
			&lt;!-- Item 1 -->
			&lt;div class="filter-list-item" style="">&lt;a href="" target="_blank">One&lt;/a>&lt;/div>
			&lt;!-- Item 2 -->
			&lt;div class="filter-list-item" style="">&lt;a href="" target="_blank">Two&lt;/a>&lt;/div>
			&lt;!-- Item 3 -->
			&lt;div class="filter-list-item" style="">&lt;a href="" target="_blank">Three&lt;/a>&lt;/div>
			&lt;!-- Item 4 -->
			&lt;div class="filter-list-item" style="">&lt;a href="" target="_blank">Four&lt;/a>&lt;/div>
			&lt;!-- Item 5 -->
			&lt;div class="filter-list-item" style="">&lt;a href="" target="_blank">Five&lt;/a>&lt;/div>
			&lt;!-- Item 6 -->
			&lt;div class="filter-list-item" style="">&lt;a href="" target="_blank">Six&lt;/a>&lt;/div>
		&lt;/div>
	&lt;/div>
&lt;/div>

&lt;!-- Keep JS with in body section -->
&lt;script type="text/javascript">

&lt;/script>
													
&lt;/body>
&lt;/html></code></pre>



<br><br><br>



<h2 class="wp-block-heading hLBRed" id="step-2-add-java-script-for-the-search-filter"><strong>Step 2: Add JavaScript for the Search Filter</strong></h2>



<br>



<p>There are two kinds of search filters. One matches exactly what you type in the search input, while the other shows multiple filter results based on each matching word in the input field. Below is the JavaScript code for both scenarios.</p>



<br>



<h3 class="wp-block-heading" id="a-search-filter-list-items-by-exact-match-javascript-code"><strong>a) Search Filter List Items by <span class="spanHT">Exact Match</span> &#8211; Javascript Code</strong></h3>



<br>



<p>Use this JS code when you want to filter items that match exactly with the text entered in the input textbox. </p>



<pre class="pchl"><code>&lt;script type="text/javascript">
	document.getElementById("myInput").addEventListener("keyup",
		<span class="key">function</span> searchFilter() {
			<span class="com">// Declare variables</span>
			<span class="key">var</span> input, filter, div, divs, a, i;
			input = document.getElementById('myInput');
			filter = input.value.toUpperCase();
			div = document.getElementById('myList');
			divs = div.getElementsByClassName('filter-list-item');

			<span class="com">// Loop through all list items, and hide those who don't match the search query</span>
			<span class="key">for</span> (i = 0; i &lt; divs.length; i++) {
				a = divs&#91;i].getElementsByTagName('a')&#91;0];
				<span class="key">if</span> (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
					divs&#91;i].style.display = '';
				} <span class="key">else</span> {
					divs&#91;i].style.display = 'none';
				}
			}

	});
&lt;/script></code></pre>



<div>In this code:</div>



<ol class="wp-block-list">
<li>adds an event listener to the HTML element with the ID <strong>&#8220;myInput&#8221;</strong>, specifically listening for the <strong>&#8220;keyup&#8221;</strong> event (when a key is released) and this will trigger <strong>&#8220;searchFilter&#8221;</strong> function</li>



<li>Retrieves the input element with the ID <strong>&#8220;myInput&#8221;</strong> and stores its value in the variable <strong>filter </strong>after converting it to uppercase.</li>



<li>Retrieves a collection of elements with the class <strong>&#8220;filter-list-item&#8221;</strong> within <strong>&#8220;myList&#8221;</strong> the container.</li>



<li>Iterates through each element with the class &#8220;filter-list-item.&#8221;</li>



<li>Retrieves the anchor element (<strong>&lt;a&gt;</strong>) within the current item.</li>



<li>Compares the uppercase content of the anchor element with the uppercase filter text. If a match is found, the item is displayed; otherwise, it is hidden. <br>To hide unmatched items use &#8211; <span class="spanHT">divs[i].style.display = &#8216;none&#8217;;</span> <br>To show matched item use &#8211; <span class="spanHT">divs[i].style.display = &#8221;;</span></li>
</ol>



<br><br>



<h3 class="wp-block-heading" id="b-filter-search-list-items-by-multi-word-match-javascript-code"><strong>b) Filter Search List Items by <span class="spanHT">Multi-Word Match</span><strong> &#8211; Javascript Code</strong></strong></h3>



<br>



<p>Use this JS code when you want to retrieve multiple search results that match all the words (split by space) entered in the input textbox.</p>



<pre class="pchl"><code>&lt;script type="text/javascript">
	document.getElementById("myInput").addEventListener("keyup",
		function searchFilter() {
			<span class="com">// Declare variables</span>
			<span class="key">var</span> input, filter, div, divs, a, i;
			
			<span class="com">// remove double spaces in between text, trim outer space and convert to uppercase</span>
			input = document.getElementById('myInput').value.replace(/\s{2,}/g, ' ').trim().toUpperCase();
			
			<span class="com">// split filter search text by space and add it in array.</span>
			arrFilters = input.split(' ');   
			
			div = document.getElementById('myList');
			divs = div.getElementsByClassName('filter-list-item');
			
			<span class="com">// if no input then show all items.</span>
			<span class="key">if</span> (input.length == 0) {
				<span class="key">for</span> (i = 0; i &lt; divs.length; i++) {
					divs&#91;i].style.display = '';						
				}
			}
			<span class="key">else</span> {
				<span class="com">// Loop through all list items</span>
				<span class="key">for</span> (i = 0; i &lt; divs.length; i++) {
					a = divs&#91;i].getElementsByTagName('a')&#91;0];
					<span class="com">// hide items by default</span>
					divs&#91;i].style.display = 'none';
					<span class="key">for</span> (j = 0; j &lt; arrFilters.length; j++) {
						<span class="com">// if list item matches with any filter array item then display it.</span>
						<span class="key">if</span> ((arrFilters&#91;j].length > 0) &amp;&amp; (a.innerHTML.toUpperCase().indexOf(arrFilters&#91;j]) > -1)) {
							divs&#91;i].style.display = '';
							<span class="key">break</span>;
						} 						
					}
					
				}
			}

	});
&lt;/script>
</code></pre>



<p>This code works similarly as explained above but with a slight difference. Instead of searching the entire text at once, it looks at each individual word. It then finds and displays items that match, resulting in multiple search filter results.</p>



<p class="brgrey">Remove toUpperCase() if you want to perform a case-sensitive search.</p>



<br><br><br>



<h2 class="wp-block-heading hLBRed" id="step-3-test-your-search-filter"><strong>Step 3: Test Your Search Filter</strong></h2>



<br><br>



<h3 class="wp-block-heading" id="test-1-exact-match-search-filter"><strong>Test 1 &#8211; Exact match search filter</strong></h3>



<br>



<div style="border: 1px solid #a9a9a9; padding: 15px;">
	<div><center><strong><u>Search and Filter Exact Text</u></strong></center></div>
	<br>
	<div>
		<div>			
			<span style="font-weight:bold; font-size: 18px; color: #555555; ">Search filter: </span>
			<input type="text" id="myInput" placeholder=" type &amp; filter..."/>
		</div>
		<div id="myList">
			<div class="filter-list-item" style=""><a href="#" target="_blank" rel="noopener">One</a></div>
			<div class="filter-list-item" style=""><a href="#" target="_blank" rel="noopener">Two</a></div>
			<div class="filter-list-item" style=""><a href="#" target="_blank" rel="noopener">Three</a></div>
			<div class="filter-list-item" style=""><a href="#" target="_blank" rel="noopener">Four</a></div>
			<div class="filter-list-item" style=""><a href="#" target="_blank" rel="noopener">Five</a></div>
			<div class="filter-list-item" style=""><a href="#" target="_blank" rel="noopener">Six</a></div>
		</div>
	</div>
</div>

<script>
document.getElementById("myInput").addEventListener("keyup",
		function searchFilter() {
			var input, filter, div, divs, a, i;
			input = document.getElementById('myInput');
			filter = input.value.toUpperCase();
			div = document.getElementById('myList');
			divs = div.getElementsByClassName('filter-list-item');

			for (i = 0; i < divs.length; i++) {
				a = divs[i].getElementsByTagName('a')[0];
				if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
					divs[i].style.display = '';
				} else {
					divs[i].style.display = 'none';
				}
			}
	});
</script>



<br><br>



<h3 class="wp-block-heading" id="test-2-multiple-search-filter-match-by-each-word"><strong>Test 2 &#8211; Multiple search filter match by each word</strong></h3>



<br>



<div style="border: 1px solid #a9a9a9; padding: 15px;">
	<div><center><strong><u>Search and Filter all Matching Words</u></strong></center></div>
	<br>
	<div>
		<div>			
			<span style="font-weight:bold; font-size: 18px; color: #555555; ">Search filter: </span>
			<input type="text" id="myInput2" placeholder=" type &amp; filter..."/>
		</div>
		<div id="myList2">
			<div class="filter-list-item" style=""><a href="#" target="_blank" rel="noopener">One</a></div>
			<div class="filter-list-item" style=""><a href="#" target="_blank" rel="noopener">Two</a></div>
			<div class="filter-list-item" style=""><a href="#" target="_blank" rel="noopener">Three</a></div>
			<div class="filter-list-item" style=""><a href="#" target="_blank" rel="noopener">Four</a></div>
			<div class="filter-list-item" style=""><a href="#" target="_blank" rel="noopener">Five</a></div>
			<div class="filter-list-item" style=""><a href="#" target="_blank" rel="noopener">Six</a></div>
		</div>
	</div>
</div>
<script>
document.getElementById("myInput2").addEventListener("keyup",
		function searchFilter() {
			var input, filter, div, divs, a, i;			
			input = document.getElementById('myInput2').value.replace(/\s{2,}/g, ' ').trim().toUpperCase();
			arrFilters = input.split(' ');   
			
			div = document.getElementById('myList2');
			divs = div.getElementsByClassName('filter-list-item');
			if (input.length == 0) {
				for (i = 0; i < divs.length; i++) {
					divs[i].style.display = '';						
				}
			}
			else {
				for (i = 0; i < divs.length; i++) {
					a = divs[i].getElementsByTagName('a')[0];
					// hide items by default
					divs[i].style.display = 'none';
					for (j = 0; j < arrFilters.length; j++) {
						// if list item matches with any filter array item then display it.
						if ((arrFilters[j].length > 0) && (a.innerHTML.toUpperCase().indexOf(arrFilters[j]) > -1)) {
							divs[i].style.display = '';
							break;
						} 						
					}
					
				}
			}
	});
</script>



<br><br>
<div class="note">
<div style="color:#00008b; font-weight:bold; border-bottom:0.125rem #00008b solid; font-style:italic;">Download Source Code &amp; Try Yourself:</div>
<div class="notepoints" style="padding-top:0.375rem"><b>Filter Search by Exact Match</b> – <a href="/img/1/searchfilter/SearchFilterByExactMatch.zip"><span class="cLink3"><b>Download</b></span></a></div>
<div class="notepoints"><b>Filter Search by Multiple Words</b> – <a href="/img/1/searchfilter/SearchFilterByMultipleWords.zip"><span class="cLink3"><b>Download</b></span></a></div>
</div>



<div id="PageInAd1"></div>
<script>
fetch('/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<style>
	input[type="text"]{
		background-color: #FFFFFF;
		border-style: solid;
		border-width: 1px;
		border-color: #cccccc;
		box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
		color: rgba(0, 0, 0, 0.75);
		height: 2.3125rem;
		margin: 0 0 1rem 0;
		padding: 0.5rem;
	}
	
	input[type="text"]:focus{
		background: #fafafa;
		border-color: #999999;
		outline: none;
	}
	
	#myList, #myList2{
		line-height: 1.6; 
		font-size: 18px; 
		overflow-y: scroll; 
		height: 200px; 
		border: 2px lightgray solid; 
		padding-left:15px;
	}
	
	#myInput, #myInput2{
		width: 80%; display:inline; border-radius: 10px;
	}
</style>



<br>
<script src="/my-js/latesttop10post.js" type="text/javascript"></script>
<input type="hidden" id="cids" value="129,138,103,104">
<div id="latestPostlist"></div>
<br>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/search-filter-div-list-items-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Validating MAC Addresses Using Regular Expressions &#8211; Javascript</title>
		<link>https://www.codeindotnet.com/mac-address-validation-regex-in-javascript/</link>
					<comments>https://www.codeindotnet.com/mac-address-validation-regex-in-javascript/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 30 Nov 2023 18:23:29 +0000</pubDate>
				<category><![CDATA[JavaScript Examples]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=6456</guid>

					<description><![CDATA[Validating a MAC address using JavaScript can be a useful task, especially in scenarios where you need to ensure that users input the correct format for MAC addresses. MAC (Media Access Control) addresses are unique identifiers assigned to network interfaces, and they follow a specific format. Here&#8217;s a guide on how to validate MAC addresses [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInHoriAd1"></div>
<script>
fetch('/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>



<p>Validating a MAC address using JavaScript can be a useful task, especially in scenarios where you need to ensure that users input the correct format for MAC addresses. MAC (Media Access Control) addresses are unique identifiers assigned to network interfaces, and they follow a specific format. Here&#8217;s a guide on how to validate MAC addresses using JavaScript with a complete HTML example.</p>



<div class="wp-block-rank-math-toc-block toc-cust" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#about-mac-address">About MAC Address</a></li><li><a href="#regex-code-snippet-to-validate-mac-address">Regex Code Snippet to Validate Mac Address</a></li><li><a href="#validating-mac-addresses-using-java-script-example">Validating MAC Addresses Using JavaScript &#8211; Example</a></li></ul></nav></div>



<br><br><br>



<h2 class="wp-block-heading hLBRed" id="about-mac-address"><strong>About MAC Address</strong></h2>



<br>



<p style="margin-bottom: 0;">MAC addresses typically follow the format <strong>XX:XX:XX:XX:XX:XX</strong> or <strong>XXXX.XXXX.XXXX</strong>, where each <strong>X</strong> represents a hexadecimal digit (0-9, A-F). A valid MAC address must meet the following criteria:</p>



<ol style="margin-bottom: 0;">
<li><strong>Length:</strong> A MAC address is 48 bits (6 bytes) long. It is usually represented as 12 hexadecimal characters, grouped in pairs separated by colons or hyphens (e.g., EA:7D:13:21:A5:44).</li>	 

<li><strong>Formatting:</strong> It can be represented in two common formats:	 
<ul>	 
<li>Six pairs of hexadecimal digits separated by hyphens or colons (e.g., 7a<b>:</b>84<b>:</b>ac<b>:</b>92<b>:</b>d9<b>:</b>15).</li>	 
<li>Three groups of four hexadecimal digits separated by dots (e.g., 01A2<b>.</b>3BCD<b>.</b>4E5F).</li>	 
</ul>	 
</li>	 
</ol>



<p>These conditions ensure a standardized way to represent MAC addresses, making them easily readable and consistent across different devices and systems.</p>



<br><br>



<h2 class="wp-block-heading hLBRed" id="regex-code-snippet-to-validate-mac-address"><strong>Regex Code Snippet to Validate Mac Address</strong></h2>



<br>



<div><b>1)</b> The regex code given below will validate 6 pairs of hexadecimal digits separated by hyphens or colons:</div>



<pre class="pchl"><code><span class="key">var</span> pattern = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/</code></pre>



<br><br>



<div><b>2)</b> This regex pattern will validate both,  &#8216;6 pairs of 2 hexadecimal digits&#8217; and as well as &#8216;3 groups of 4 hexadecimal digits&#8217;, separated by hyphens or colons:</div>



<pre class="pchl"><code><span class="key">var</span> pattern = /^(&#91;0-9A-Fa-f]{2}&#91;:-]){5}(&#91;0-9A-Fa-f]{2})|(&#91;0-9a-fA-F]{4}.&#91;0-9a-fA-F]{4}.&#91;0-9a-fA-F]{4})$/</code></pre>



<br><br><div><b><i><u>code snippet:</u></i></b></div>



<pre class="pchl"><code><span class="key">function</span> isValidMacAddress(macAddress) {
    <span class="com">// Regular expression for validating MAC addresses</span>
    <span class="key">const</span> macRegex = /^(&#91;0-9A-Fa-f]{2}&#91;:-]){5}(&#91;0-9A-Fa-f]{2})|(&#91;0-9a-fA-F]{4}.&#91;0-9a-fA-F]{4}.&#91;0-9a-fA-F]{4})$/;

    <span class="key">return</span> macRegex.test(macAddress);
}
</code></pre>



<p style="margin-bottom: 0;">In this function:</p>



<ul>
<li><span class="spanHT"><strong>^</strong></span>: Asserts the start of the string.</li>



<li><span class="spanHT">([0-9A-Fa-f]{2}[:-]){5}</span>: This part matches the first five groups of two hexadecimal digits separated by either a colon <span class="spanHT"><strong>:</strong></span> or a hyphen <span class="spanHT"><strong>–</strong></span>.
<ul>
<li><span class="spanHT">([0-9A-Fa-f]{2}[:-])</span>: This part captures a group of two hexadecimal digits followed by either a colon or a hyphen.</li>



<li><span class="spanHT">{5}</span>: Specifies that the preceding group should occur exactly 5 times.</li>
</ul>
</li>



<li><span class="spanHT">([0-9A-Fa-f]{2})</span>: Matches the last group of two hexadecimal digits.</li>



<li><span class="spanHT"><strong>|</strong></span>: Acts as an OR operator, allowing the regex to match either the MAC address format or the custom format.</li>



<li><span class="spanHT">([0-9a-fA-F]{4}\.[0-9a-fA-F]{4}\.[0-9a-fA-F]{4})</span>: This part matches a custom format where three groups of four hexadecimal digits are separated by dots <span class="spanHT"><strong>.</strong></span>.
<ul>
<li><span class="spanHT">([0-9a-fA-F]{4}\.[0-9a-fA-F]{4}\.[0-9a-fA-F]{4})</span>: This part captures three groups of four hexadecimal digits separated by dots.</li>
</ul>
</li>



<li><span class="spanHT"><strong>$</strong></span>: Asserts the end of the string.</li>
</ul>



<p>The function returns <strong>true </strong>if the MAC address is valid and <strong>false </strong>otherwise.</p>



<br><br>



<h2 class="wp-block-heading hLBRed" id="validating-mac-addresses-using-java-script-example"><strong>Validating MAC Addresses Using JavaScript &#8211; Example</strong></h2>



<br>



<p>Let&#8217;s create a simple HTML example that utilizes the JavaScript function for MAC address validation. Here is the full HTML code;</p>



<div><b><i><u>.html file:</u></i></b><button class="c-b-s-f-r" onclick="ctc('div1',this)">Copy code</button></div>



<div id="div1">
<pre class="pchl"><code>&lt;!DOCTYPE html>
&lt;html lang="en">
&lt;head>
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>MAC Address Validation&lt;/title>
    &lt;style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin: 20px;
        }

        #macInput {
            padding: 8px;
            font-size: 16px;
        }

        #result {
            margin-top: 10px;
            color: green;
            font-weight:bold;
        }

        #error {
            margin-top: 10px;
            color: red;
        }
    &lt;/style>
&lt;/head>
&lt;body>

    &lt;h2>MAC Address Validation&lt;/h2>

    &lt;label for="macInput">Enter MAC Address:&lt;/label>
    &lt;input type="text" id="macInput" placeholder="e.g., 00:1A:2B:3C:4D:5E">

    &lt;button onclick="<span style="background:#f2f19d;">validateMAC()</span>">Validate&lt;/button>

    &lt;div id="result">&lt;/div>
    &lt;div id="error">&lt;/div>

    &lt;script>
        <span class="key">function</span> <span style="background:#f2f19d;">validateMAC()</span> {
            <span class="key">var</span> macInput = document.getElementById("macInput").value;
            <span class="key">var</span> macRegex = <span style="background:#f2f19d;">/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})|([0-9a-fA-F]{4}.[0-9a-fA-F]{4}.[0-9a-fA-F]{4})$/</span>;

            <span class="key">if</span> (macRegex.test(macInput)) {
                document.getElementById("result").innerText = "Valid MAC Address!";
                document.getElementById("error").innerText = "";
            } <span class="key">else</span> {
                document.getElementById("result").innerText = "";
                document.getElementById("error").innerText = "Invalid MAC Address. Please enter a valid MAC address.";
            }
        }
    &lt;/script>

&lt;/body>
&lt;/html>
</code></pre>
</div>



<p style="margin-bottom: 0;">In this example:</p>



<ul class="wp-block-list">
<li>We have an input field for the user to enter a MAC address.</li>



<li>There&#8217;s a &#8220;Validate&#8221; button that triggers the <strong>validateMac() </strong>function when clicked.</li>



<li>The result of the validation is displayed below the button.</li>
</ul>



<p>Feel free to copy and paste this HTML code into an HTML file and open it in your web browser to see the MAC address validation in action. </p>



<p>Enter different MAC addresses to observe how the validation result changes.</p>



<div><b><i><u>example &#8211; input &amp; output:</u></i></b></div>
<br>
<div>
<b>Test Case 1:</b><br>
7a-84-ac-92-d9-15<span style="color: green; font-weight:bold; padding-left:0.9375rem;">// Valid</span><br><br>
<b>Test Case 2:</b><br>
09:df:b7:b5:42:44<span style="color: green; font-weight:bold; padding-left:0.9375rem;">// Valid</span><br><br>
<b>Test Case 3:</b><br>
01A2.3BCD.4E5F<span style="color: green; font-weight:bold; padding-left:0.9375rem;">// Valid</span><br><br><br>

<b>Test Case 4:</b><br>
GHIJ.KLMN.OPQR<span style="color: red; font-weight:bold; padding-left:0.9375rem;">// Invalid</span><br><br>
<b>Test Case 5:</b><br>
98-76-54-AH&#8211;32-21<span style="color: red; font-weight:bold; padding-left:0.9375rem;">// Invalid</span>
</div>



<br><br><br>



<h2 class="wp-block-heading hLBRed" id="screenshots"><strong>Screenshots</strong></h2>



<br>



<p>Here are the test results of valid &amp; invalid MAC addresses.</p>



<div><b><i><u>1) valid mac address with colon separated:</u></i></b></div>



<figure class="wp-block-image size-full"><img decoding="async" width="438" height="118" src="https://www.codeindotnet.com/wp-content/uploads/2023/11/mac-address-validation-colon-separated-javascript.jpg" alt="mac address validation colon separated javascript" class="wp-image-6483" srcset="https://www.codeindotnet.com/wp-content/uploads/2023/11/mac-address-validation-colon-separated-javascript.jpg 438w, https://www.codeindotnet.com/wp-content/uploads/2023/11/mac-address-validation-colon-separated-javascript-300x81.jpg 300w" sizes="(max-width: 438px) 100vw, 438px" /></figure>



<br><br><div><b><i><u>2) valid mac address with hypen separated:</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/macaddvalidation/mac-address-validation-hypen-separated-javascript.jpg" alt="mac address validation hypen separated javascript"/></figure>



<br><br><div><b><i><u>3) valid mac address with dot separated(3 pairs of four hexadecimal digits):</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/macaddvalidation/mac-address-validation-dots-separated-javascript.jpg" alt="mac address validation dots separated javascript"/></figure>



<br><br><div><b><i><u>4) invalid mac address with hypen separated:</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/macaddvalidation/invalid-mac-address-validation-hypen-separated-javascript.jpg" alt="invalid mac address validation hypen separated javascript"/></figure>



<br><br><div><b><i><u>4) invalid mac address with dot separated &#038; four hexadecimal digits:</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/macaddvalidation/invalid-mac-address-validation-dots-separated-javascript.jpg" alt="invalid mac address validation dots separated javascript"/></figure>



<div id="PageInAd1"></div>
<script>
fetch('/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<script src="/my-js/latesttop10post.js" type="text/javascript"></script>
<input type="hidden" id="cids" value="129,138,103,104">
<div id="latestPostlist"></div>
<br>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/mac-address-validation-regex-in-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Share to WhatsApp link button from Website using Javascript: 3 Ways</title>
		<link>https://www.codeindotnet.com/whatsapp-share-button-api-link-javascript/</link>
					<comments>https://www.codeindotnet.com/whatsapp-share-button-api-link-javascript/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Fri, 17 Nov 2023 16:32:33 +0000</pubDate>
				<category><![CDATA[JavaScript Examples]]></category>
		<category><![CDATA[share content to whatsapp api link javascript]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=5797</guid>

					<description><![CDATA[Given WhatsApp&#8217;s status as the leading messaging application, many websites find it essential to include a WhatsApp sharing feature. Adding a WhatsApp share button to your website can indeed enhance the user experience and promote content sharing. To implement a social media sharing feature on your website, you can use the WhatsApp API or Web [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInHoriAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>



<p>Given WhatsApp&#8217;s status as the leading messaging application, many websites find it essential to include a WhatsApp sharing feature. Adding a WhatsApp share button to your website can indeed enhance the user experience and promote content sharing. To implement a social media sharing feature on your website, you can use the WhatsApp API or Web URL. In this article, we&#8217;ll show you the steps to add a WhatsApp share text link to your website using JavaScript.</p>



<br>



<h2 class="wp-block-heading h2Cust1" id="add-share-to-whats-app-link-to-your-website">Add &#8216;Share to WhatsApp&#8217; link to Your Website</h2>



<br>



<p>The web developer needs to meet this requirement by integrating the WhatsApp sharing option into their website to enhance user efficiency. This allows users to effortlessly share information directly from the website using the dedicated sharing option, eliminating the need for manual copying and pasting. Usually, 3 ways to do it and they are;</p>



<br>



<h2 class="wp-block-heading" id="different-ways-to-share-whatsapp-message-links">Different Ways to share Whatsapp message links</h2>



<figure class="wp-block-table"><table><thead><tr><th class="has-text-align-center" data-align="center">Different Ways</th><th>Links</th><th class="has-text-align-center" data-align="center">Mobile<br>App</th><th class="has-text-align-center" data-align="center">Desktop<br>App</th><th class="has-text-align-center" data-align="center">Browser<br>(New Tab)</th></tr></thead><tbody><tr><td class="has-text-align-center" data-align="center">Method 1</td><td>api.whatsapp.com/send</td><td class="has-text-align-center" data-align="center"><img src="https://s.w.org/images/core/emoji/16.0.1/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /></td><td class="has-text-align-center" data-align="center"><img src="https://s.w.org/images/core/emoji/16.0.1/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /></td><td class="has-text-align-center" data-align="center"><img src="https://s.w.org/images/core/emoji/16.0.1/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /></td></tr><tr><td class="has-text-align-center" data-align="center">Method 2</td><td>whatsapp://send</td><td class="has-text-align-center" data-align="center"><img src="https://s.w.org/images/core/emoji/16.0.1/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /></td><td class="has-text-align-center" data-align="center"><img src="https://s.w.org/images/core/emoji/16.0.1/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /></td><td class="has-text-align-center" data-align="center"><img src="https://s.w.org/images/core/emoji/16.0.1/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /></td></tr><tr><td class="has-text-align-center" data-align="center">Method 3</td><td>web.whatsapp.com/send</td><td class="has-text-align-center" data-align="center"><img src="https://s.w.org/images/core/emoji/16.0.1/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /></td><td class="has-text-align-center" data-align="center"><img src="https://s.w.org/images/core/emoji/16.0.1/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /></td><td class="has-text-align-center" data-align="center"><img src="https://s.w.org/images/core/emoji/16.0.1/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /></td></tr></tbody></table></figure>



<p>Regardless of the method chosen, the user needs to be either logged into the WhatsApp application or linked to a device to share text links with individuals listed in their contacts because WhatsApp facilitates private sharing, ensuring that content is shared among a select group of individuals rather than with the public at large. <br>Let&#8217;s explore all the methods one by one;</p>



<br>



<h3 class="wp-block-heading hLBRed" id="method-1-using-whats-app-api-link-recommended"><strong>Method 1 &#8211; Using WhatsApp API link <sup><span style="background-color: #90ee90; padding: 0.0625rem 0.3125rem; border-radius:0.625rem; font-size:16px">recommended</span></sup></strong></h3>



<br>



<p>Using the <strong>WhatsApp API</strong> approach is recommended for sharing text messages and links from the user&#8217;s WhatsApp application on either Mobile or Desktop.</p>



<p><em><span style="text-decoration: underline;"><strong>example</strong></span>:</em> <a href="https://api.whatsapp.com/send?text=YourTextHere" target="_blank" rel="noopener">https://api.whatsapp.com/send?text=YourTextHere</a></p>



<p>To create a WhatsApp share button or link that works on both mobile and Desktop, you can use the below code that will work on both platforms.</p>



<div><b><i><u>javascript code snippet</u></i></b></div>



<pre class="pchl"><code>window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(shareMessage)}`, '_blank');</code></pre>



<br><br>



<h4 class="wp-block-heading" id="html-code-to-send-whatsapp-message"><strong><em><span style="text-decoration: underline;">html code to send whatsapp message</span></em></strong></h4>



<pre class="pchl"><code>&lt;!DOCTYPE html>
&lt;html>
&lt;head>
    &lt;title>WhatsApp Share Button&lt;/title>
&lt;/head>
&lt;body>
	&lt;br>
	&lt;h1>Method 1 - Sharing WhatsApp text using API&lt;/h1>
	&lt;br>
	&lt;button id="whatsapp-btn1">Share on WhatsApp&lt;/button>

    &lt;script>
        <span class="com">// Function to open WhatsApp with pre-filled message</span>
        <span class="key">function</span> shareOnWhatsApp1() { 
            <span class="com">// Replace 'YourShareMessage' and 'YourShareURL or Text' with your own message and URL</span>
            <span class="key">const</span> shareMessage = <span class="str">'Check out this awesome website: https://www.codeindotnet.com/'</span>;
			
			<span class="com">// Invoke WhatsApp Application</span>
            window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(shareMessage)}`, '_blank');					
        }

        <span class="com">// Attach the shareOnWhatsApp function to the button click event</span>
        document.getElementById(<span class="str">'whatsapp-btn1'</span>).addEventListener(<span class="str">'click'</span>, shareOnWhatsApp1);
    &lt;/script>
&lt;/body>
&lt;/html>
</code></pre>



<br>



<p>In the above example, a button is used to launch the WhatsApp application, but alternatively, you can use a hyperlink(anchor &lt;a&gt; tag) or an Image link as well to share content.</p>



<div><b><i><u>example &#8211; using &lt;a&gt;a tag</u></i></b></div>



<pre class="pchl"><code>&lt;a href="https://api.whatsapp.com/send?text=YourTextHere" target="_blank">Share to Whatsapp&lt;/a></code></pre>



<br><br><br>



<h3 class="wp-block-heading hLBRed" id="method-2-using-url-alternative-to-whats-app-api"><strong>Method 2: Using URL &#8211; Alternative to WhatsApp API</strong></h3>



<br>



<p>This method functions similarly to the previous one &#8211; the only difference is instead of the API, a WhatsApp URL can be utilized.</p>



<p><strong><em><span style="text-decoration: underline;">example:</span></em></strong> <a href="whatsapp://send?text=">whatsapp://send?text=YourTextLinkHere</a></p>



<br>



<div><b><i><u>javascript code snippet</u></i></b></div>



<pre class="pchl"><code>window.location.href = `whatsapp://send?text=${encodeURIComponent(shareMessage)}`;</code></pre>



<br><br>



<h4 class="wp-block-heading" id="whatsapp-share-javascript-code"><strong><em><span style="text-decoration: underline;">whatsapp share javascript code</span></em></strong></h4>



<pre class="pchl"><code>&lt;!DOCTYPE html>
&lt;html>
&lt;head>
    &lt;title>WhatsApp Share Button&lt;/title>
&lt;/head>
&lt;body>
	&lt;br>
	&lt;h1>Method 2 - Sharing WhatsApp text using URL&lt;/h1>
	&lt;br>
	&lt;button id="whatsapp-btn2">Share on WhatsApp&lt;/button>

    &lt;script>
        <span class="key">function</span> shareOnWhatsApp2() {
            <span class="key">const</span> shareMessage = <span class="str">'Check out this awesome website: https://www.codeindotnet.com/'</span>;
			
            window.location.href = `whatsapp://send?text=${encodeURIComponent(shareMessage)}`;					
        }

        document.getElementById(<span class="str">'whatsapp-btn2'</span>).addEventListener(<span class="str">'click'</span>, shareOnWhatsApp2);
    &lt;/script>
&lt;/body>
&lt;/html>
</code></pre>



<br><br><br>



<p><strong><span style="text-decoration: underline;">Screenshots</span></strong>:</p>



<p>When you run the provided code, it will display a button to share defined text or links to WhatsApp.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/wtsapp/sharing-link-message-on-whatsapp-example.jpg" alt="sharing link message on whatsapp example"/></figure>



<br>



<p>Click on the &#8220;Share to WhatsApp&#8221; button. </p>



<p>On a desktop device, a popup box will appear asking for permission to open the WhatsApp application. <br>Click on &#8216;<strong>Open WhatsApp</strong>&#8216; and this action will redirect to the user&#8217;s WhatsApp application, as shown in the screenshot.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/wtsapp/open-whatsapp-from-javascript.jpg" alt="open whatsapp from javascript"/></figure>



<br>



<p><mark style="background-color:rgba(0, 0, 0, 0)" class="has-inline-color has-vivid-red-color"><strong><em>Note:</em></strong></mark> On a mobile device, WhatsApp will open directly without a pop-up.</p>



<p>Once the app is opened, it allows users to share messages or text links with existing WhatsApp contacts (same as forwarding messages to multiple contacts).</p>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/wtsapp/share-message-text-link-to-whatsapp-contacts.jpg" alt="share message text link to whatsapp contacts"/></figure>



<br>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/wtsapp/share-text-link-to-whatsapp-from-mobile-device.jpg" alt="share text link to whatsapp from mobile device"/></figure>



<br><br><br><br>



<h3 class="wp-block-heading hLBRed" id="method-3-using-whats-app-web-link"><strong>Method 3: Using WhatsApp Web Link </strong></h3>



<br>



<p>In this approach, the WhatsApp Web link will open exclusively in the browser, prompting you to link the device in order to share messages with the user&#8217;s contact list.</p>



<p><strong><em><span style="text-decoration: underline;">example:</span></em></strong> <a href="https://web.whatsapp.com/send?text=YourTextMessageHere" target="_blank" rel="noopener">https://web.whatsapp.com/send?text=YourTextMessageHere</a></p>



<br>



<div><b><i><u>javascript code snippet</u></i></b></div>



<pre class="pchl"><code>window.open(`https://web.whatsapp.com/send?text=${encodeURIComponent(shareMessage)}`, '_blank');</code></pre>



<br><br>



<h4 class="wp-block-heading" id="share-link-text-from-whatsapp-javascript-code"><strong><em><span style="text-decoration: underline;">share link text from whatsapp javascript code</span></em></strong></h4>



<pre class="pchl"><code>&lt;!DOCTYPE html>
&lt;html>
&lt;head>
    &lt;title>WhatsApp Share Button&lt;/title>
&lt;/head>
&lt;body>
    &lt;br>
	&lt;h1>Method 3 - Using 'web.whatsapp.com' URL&lt;/h1>
	&lt;br>
	&lt;button id="whatsapp-btn3">Share on WhatsApp&lt;/button>

    &lt;script>
        <span class="key">function</span> shareOnWhatsApp3() {
            <span class="key">const</span> shareMessage = <span class="str">'Check out this awesome website: https://www.codeindotnet.com/'</span>;
			
            window.open(`https://web.whatsapp.com/send?text=${encodeURIComponent(shareMessage)}`, '_blank');					
        }

        document.getElementById(<span class="str">'whatsapp-btn3'</span>).addEventListener(<span class="str">'click'</span>, shareOnWhatsApp3);
    &lt;/script>
&lt;/body>
&lt;/html>
</code></pre>



<br>



<p>Whether on mobile or desktop, the <strong>web.whatsapp.com</strong> link will only open in the browser tab, as shown below.</p>



<div><b><i><u>Desktop Screenshot</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/wtsapp/whatsapp-web-link-send-text-link.jpg" alt="whatsapp web link send text link"/></figure>



<br><div><b><i><u>Mobile Screenshot</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/1/wtsapp/whatsapp-web-share-link.jpg" alt="whatsapp web share link on browser tab"/></figure>



<br><br><br>



<h3 class="wp-block-heading hLBRed" id="if-condition-optional-code">&#8216;if&#8217; condition &#8211; optional code</h3>



<br>



<p>If you want to add specific code based on the device, use an <span class="spanHT">if</span> condition to execute your logic. </p>



<div><b><i><u>if condition &#8211; example</u></i></b></div>



<pre class="pchl"><code>function shareOnWhatsApp() {
	<span class="com">// Replace 'YourShareMessage' and 'YourShareURL' with your own message and URL</span>
	<span class="key">const</span> shareMessage = 'Check out this awesome website: https://www.codeindotnet.com/';
	
	<span class="key">if</span>(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
		<span class="com">// Mobile device, open WhatsApp with pre-filled message</span>
		<span class="key">const</span> whatsappLink = `whatsapp://send?text=${encodeURIComponent(shareMessage)}`;
		window.location.href = whatsappLink;
	} 
	<span class="key">else</span> {
		<span class="com">// Desktop device, provide a WhatsApp Web link</span>
		<span class="key">const</span> whatsappWebLink = `https://web.whatsapp.com/send?text=${encodeURIComponent(shareMessage)}`;
		window.open(whatsappWebLink, '_blank');
	}
}
</code></pre>



<br>



<p>In this example, if you&#8217;re on a mobile device, the code &#8216;<strong>whatsapp://send</strong>&#8216; will run, and if it is a desktop device, the code &#8216;<strong>web.whatsapp.com/send</strong>&#8216; will be executed.</p>



<div id="PageInAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<br>
<script src="/my-js/latesttop10post.js" type="text/javascript"></script>
<input type="hidden" id="cids" value="129,138,103,140,139,141">
<div id="latestPostlist"></div>
<br>



<br>



<div class="wp-block-rank-math-toc-block toc-cust" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#different-ways-to-share-whatsapp-message-links">Different Ways to share Whatsapp message links</a><ul><li><a href="#method-1-using-whats-app-api-link-recommended">Method 1 &#8211; Using WhatsApp API link recommended</a><ul></ul></li><li><a href="#method-2-using-url-alternative-to-whats-app-api">Method 2: Using URL &#8211; Alternative to WhatsApp API</a><ul></ul></li><li><a href="#method-3-using-whats-app-web-link">Method 3: Using WhatsApp Web Link </a><ul></ul></li></ul></li></ul></nav></div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/whatsapp-share-button-api-link-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to show Page Loading div icon until the page has finished loading?</title>
		<link>https://www.codeindotnet.com/show-page-loading-div-spinner-icon-until-the-page-has-finished-loading/</link>
					<comments>https://www.codeindotnet.com/show-page-loading-div-spinner-icon-until-the-page-has-finished-loading/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 23 Sep 2023 06:51:21 +0000</pubDate>
				<category><![CDATA[JavaScript Examples]]></category>
		<category><![CDATA[document.readyState property]]></category>
		<category><![CDATA[readystatechange event]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=5430</guid>

					<description><![CDATA[Show spinner image while the page is loading &#8211; javascript In the fast-paced world of web development, user experience is paramount. It&#8217;s crucial to keep your visitors engaged and informed, especially when your website takes a little extra time to load. One way to enhance the user experience is by displaying a loading or spinner [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInHoriAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>



<h2 class="wp-block-heading">Show spinner image while the page is loading &#8211; javascript</h2>



<p class="custp1">In the fast-paced world of web development, user experience is paramount. It&#8217;s crucial to keep your visitors engaged and informed, especially when your website takes a little extra time to load. One way to enhance the user experience is by displaying a loading or spinner div icon until the page has fully loaded. In this article, we&#8217;ll explore how to achieve this effect using pure vanilla JavaScript and the <span class="spanHT">document.readyState</span> property. Whenever the value of this property undergoes a change, it triggers a <span class="spanHT">readystatechange</span> event on the document object.</p>



<br>



<h2 class="wp-block-heading h2Cust1"><strong>Implementing the Page Loading Div with document.readyState</strong></h2>



<br>



<p>Let&#8217;s go through the steps to create a loading div that appears until the page has finished loading using pure JavaScript and the document.readyState property:</p>



<h3 class="wp-block-heading"><strong>Why Use document.readyState?</strong></h3>



<p class="custp1">The <span class="spanHT">document.readyState</span> property is a valuable tool in JavaScript that allows us to monitor the loading status of a web page. It has different values at various stages of the page-loading process, making it perfect for showing a loading div icon until the page is ready for interaction. This approach is efficient because it doesn&#8217;t rely on additional libraries or external dependencies.</p>



<br>



<h4 class="wp-block-heading hLBRed"><strong><em><span style="text-decoration: underline;">HTML Structure:</span></em></strong></h4>



<p class="custp1">Begin by setting up the basic HTML structure of your page. Place a div element for the loading icon or message directly after the opening <span class="spanHT">&lt;body&gt;</span> tag in your HTML file:</p>



<pre class="pchl"><code>&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;!-- Your head content here --&gt;
&lt;/head&gt;

&lt;body&gt;

	<span style="background:#f2f19d;">&lt;div id="maindivblock"&gt;</span>
	<span style="background:#f2f19d;">&lt;div id="loader" class="center"&gt;&lt;/div&gt;</span>

	&lt;!-- Your page content here --&gt;

	<span style="background:#f2f19d;">&lt;/div&gt;</span>

	<span style="background:#f2f19d;">&lt;script src="your-script.js"&gt;&lt;/script&gt;</span>

&lt;/body&gt;
&lt;/html&gt;</code></pre>



<br><br>



<h4 class="wp-block-heading hLBRed"><strong><em><span style="text-decoration: underline;">CSS Styling:</span></em></strong></h4>



<p class="custp1">Style the loading div to match your website&#8217;s design. You can center it on the screen, set a background color, and apply CSS animations to make it visually appealing. Here&#8217;s a basic example:</p>



<pre class="pchl"><code>&lt;style&gt;
	#loader {
		border: 12px solid #f3f3f3;
		border-radius: 50%;
		border-top: 12px solid #444444;
		width: 70px;
		height: 70px;
		animation: spin 1s linear infinite;
	}

	.center {
		position: absolute;
		top: 0;
		bottom: 0; <span class="com">// comment this line if not required.</span>
		left: 0;
		right: 0;
		margin: auto;
	}

	@keyframes spin {
		100% {
			transform: rotate(360deg);
		}
	}
&lt;/style&gt;</code></pre>



<br><br>



<h4 class="wp-block-heading hLBRed"><strong><em><span style="text-decoration: underline;">JavaScript Logic:</span></em></strong></h4>



<p class="custp1">Now, let&#8217;s add the JavaScript logic to show the loading div until the page has finished loading. Create a JavaScript file (e.g., <strong>your-script.js</strong>) and add the following code:</p>



<h5 class="wp-block-heading">Use the <span class="spanHT">onreadystatechange</span> event to show the loading indicator while loading the page</h5>



<br><div><b><i><u>your-script.js</u></i></b></div>



<pre class="pchl"><code>
document.onreadystatechange = <span class="key">function</span> () {
	if (document.readyState !== "complete") {
		<span class="com">//document.querySelector("body").style.visibility = "hidden";</span>
		document.getElementById("maindivblock").style.display = "none";
		document.querySelector("#loader").style.visibility = "visible";
	} else {
		document.querySelector("#loader").style.display = "none";
		document.getElementById("maindivblock").style.display = "block";
		<span class="com">//document.querySelector("body").style.visibility = "visible";</span>
	}
};</code></pre>



<br>



<div class="note">
<div style="color:#00008b; font-weight:bold; border-bottom:0.125rem #00008b solid; font-style:italic;">Note:</div>
<div style="padding-top:0.375rem">In this example, loader is implemented within <span class="spanHT">&lt;div&gt;</span> tag but if you want to apply loader/spinner for the whole <span class="spanHT">&lt;body&gt;</span> (page) section then uncomment <b>querySelector(&#8220;body&#8221;)</b> line and comment <b>maindivblock</b> line.</div>
</div>



<p class="custp1">In this JavaScript code, we first listen for the &#8220;<strong>DOMContentLoaded</strong>&#8221; event, which triggers when the DOM content is fully loaded. At this point, we display the loading div.</p>



<p>Next, we use the <strong>document.onreadystatechange</strong> event to continuously check the value of <strong>document.readyState</strong>. When <strong>document.readyState</strong> becomes &#8220;<strong>complete</strong>&#8220;, it means the entire page has finished loading, and we hide the loading div.</p>



<br>



<h4 class="wp-block-heading hLBRed"><strong><em><span style="text-decoration: underline;">Screenshot:</span></em></strong></h4>



<figure class="wp-block-image size-full is-style-default"><img decoding="async" width="785" height="309" style="border: 1px solid;" src="https://www.codeindotnet.com/wp-content/uploads/2023/09/show-page-loading-div-spinner-icon-until-the-page-has-finished-loading-data.jpg" alt="show page loading div spinner icon until the page has finished loading data" class="wp-image-5455" srcset="https://www.codeindotnet.com/wp-content/uploads/2023/09/show-page-loading-div-spinner-icon-until-the-page-has-finished-loading-data.jpg 785w, https://www.codeindotnet.com/wp-content/uploads/2023/09/show-page-loading-div-spinner-icon-until-the-page-has-finished-loading-data-300x118.jpg 300w, https://www.codeindotnet.com/wp-content/uploads/2023/09/show-page-loading-div-spinner-icon-until-the-page-has-finished-loading-data-768x302.jpg 768w" sizes="(max-width: 785px) 100vw, 785px" /></figure>



<br>
<div id="PageInAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<h2 class="wp-block-heading"><strong>Conclusion</strong></h2>



<p class="custp1">Displaying a page-loading div icon or message until the page has fully loaded is an excellent way to enhance the user experience on your website. By using pure JavaScript and the document.readyState property, you can ensure that users receive visual feedback and remain engaged while your page loads. Customize the loading div&#8217;s style to match your site&#8217;s design, creating a positive first impression for your visitors.</p>



<br>
<div style="padding: 0.625rem 1.25rem 1.25rem 1.25rem; box-shadow: 0.0625rem 0.0625rem 0.9375rem 0rem lightgrey; margin-bottom: 1.25rem; border-radius: 0.625rem;">
	<div><span style="border-bottom: 0.0625rem solid #cd5c5c; color:#cd5c5c;"><b><i>Latest:</i></b></span>
		<div id="latestPostlist" style="padding-left:0.9375rem; padding-top:0.625rem; line-height: 1.9; font-weight:bold;"><div class="filter-list-item">&#8211; <a href="/take-10-items-from-data-list-javascript-jquery/" target="_blank" rel="noopener">Take Top 10 Items from Data Array List Using JavaScript and jQuery</a></div><div class="filter-list-item">&#8211; <a href="/remove-readonly-property-javascript-jquery/" target="_blank" rel="noopener">Removing the Readonly Property with JavaScript and jQuery</a></div><div class="filter-list-item">&#8211; <a href="/difference-between-window-onload-and-document-ready/" target="_blank" rel="noopener">Difference between window.onload and $(document).ready()</a></div><div class="filter-list-item">&#8211; <a href="/make-readonly-textbox-runtime/" target="_blank" rel="noopener">Switch Textbox to readonly in runtime</a></div><div class="filter-list-item">&#8211; <a href="/validate-password-with-regex-pattern-in-javascript/" target="_blank" rel="noopener">Validate Password with Regex Pattern in JS</a></div><div class="filter-list-item">&#8211; <a href="/remove-comma-using-javascript-or-jquery/" target="_blank" rel="noopener">Remove Comma in Javascript and jQuery</a></div><div class="filter-list-item">&#8211; <a href="/get-letters-alphabet-array-javascript/" target="_blank" rel="noopener">Create an Array of Alphabet characters in JavaScript</a></div><div class="filter-list-item">&#8211; <a href="/days-array-in-js-and-jquery/" target="_blank" rel="noopener">Days Array in JS and jQuery</a></div><div class="filter-list-item">&#8211; <a href="/remove-last-tr-tag-element-from-table/" target="_blank" rel="noopener">Remove last tr (row) from table &#8211; Javascript &amp; jQuery</a></div><div class="filter-list-item">&#8211; <a href="/months-array-list-in-javascript-and-jquery/" target="_blank" rel="noopener">How to access Months Array in Javascript and jQuery</a></div></div>
	</div>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/show-page-loading-div-spinner-icon-until-the-page-has-finished-loading/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Validate Password with Regex Pattern in JS</title>
		<link>https://www.codeindotnet.com/validate-password-with-regex-pattern-in-javascript/</link>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 04 Sep 2023 17:30:26 +0000</pubDate>
				<category><![CDATA[JavaScript Examples]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=4843</guid>

					<description><![CDATA[You can use JavaScript to validate a password with the given regex pattern Regex Password Patterns: // Minimum eight characters, at least one letter and one number: "^(?=.*&#91;A-Za-z])(?=.*\d)&#91;A-Za-z\d]{8,}$" // Minimum eight characters, at least one letter, one number and one special character: "^(?=.*&#91;A-Za-z])(?=.*\d)(?=.*&#91;@$!%*#?&#38;])&#91;A-Za-z\d@$!%*#?&#38;]{8,}$" // Minimum eight characters, at least one uppercase letter, one lowercase letter [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInAd1"></div>
<script>

fetch('https://www.codeindotnet.com/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<p>You can use JavaScript to validate a password with the given regex pattern</p>



<h2 class="wp-block-heading"><strong>Regex Password Patterns:</strong></h2>



<pre class="pchl"><code>
<h3 style="font-size:18px"><span class="com">// Minimum eight characters, at least one letter and one number:</span></h3>
"^(?=.*&#91;A-Za-z])(?=.*\d)&#91;A-Za-z\d]{8,}$"

<h3 style="font-size:18px"><span class="com">// Minimum eight characters, at least one letter, one number and one special character:</span></h3>
"^(?=.*&#91;A-Za-z])(?=.*\d)(?=.*&#91;@$!%*#?&amp;])&#91;A-Za-z\d@$!%*#?&amp;]{8,}$"

<h3 style="font-size:18px"><span class="com">// Minimum eight characters, at least one uppercase letter, one lowercase letter and one number:</span></h3>
"^(?=.*&#91;a-z])(?=.*&#91;A-Z])(?=.*\d)&#91;a-zA-Z\d]{8,}$"

<h3 style="font-size:18px"><span class="com">// Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character:</span></h3>
"^(?=.*&#91;a-z])(?=.*&#91;A-Z])(?=.*\d)(?=.*&#91;@$!%*?&amp;])&#91;A-Za-z\d@$!%*?&amp;]{8,}$"

<h3 style="font-size:18px"><span class="com">// Minimum eight and maximum 10 characters, at least one uppercase letter, one lowercase letter, one number and one special character:</span></h3>
"^(?=.*&#91;a-z])(?=.*&#91;A-Z])(?=.*\d)(?=.*&#91;@$!%*?&amp;])&#91;A-Za-z\d@$!%*?&amp;]{8,10}$"
</code></pre>



<br><br>



<h2 class="wp-block-heading"><strong>Validate Password with Regex &#8211; Javascript Code Example</strong></h2>



<br>



<p>Full HTML code example that includes a simple form for validating a password using JavaScript:</p>



<div><b><i><u>code snippet/ example:</u></i></b></div>



<pre class="pchl"><code>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Password Validation&lt;/title&gt;
    &lt;script&gt;
        <span class="key">function</span> validatePassword() {
            <span class="key">const</span> passwordInput = document.getElementById("password");
            <span class="key">const</span> <span style="background:#f2f19d;">password = passwordInput.value</span>;

            <span class="com">// Define the regex pattern for the password</span>
            <span class="key">const</span> <span style="background:#f2f19d;">passwordPattern = /^(?=.*&#91;A-Za-z])(?=.*\d).{8,}$/;</span>

            <span class="com">// Test if the password matches the pattern</span>
            <span class="key">if</span> (<span style="background:#f2f19d;">passwordPattern.test(password)</span>) {
                alert("Password is valid!");
            } <span class="key">else</span> {
                alert("Password is invalid. It should be at least eight characters long and contain at least one letter and one number.");
            }
        }
    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Password Validation&lt;/h1&gt;
    &lt;form&gt;
        &lt;label for="password"&gt;Password:&lt;/label&gt;
        &lt;input type="password" <span style="background:#f2f19d;">id="password"</span> name="password" required&gt;
        &lt;br&gt;
        &lt;button type="button" <span style="background:#f2f19d;">onclick="validatePassword()"</span>&gt;Validate Password&lt;/button&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>



<div id="PageInAd2"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInAd2.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd2').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd2:', error);
	});
</script>



<br>
<div style="padding: 0.625rem 1.25rem 1.25rem 1.25rem; box-shadow: 0.0625rem 0.0625rem 0.9375rem 0rem lightgrey; margin-bottom: 1.25rem; border-radius: 0.625rem;">
	<div><span style="border-bottom: 0.0625rem solid #cd5c5c; color:#cd5c5c;"><b><i>popular readings:</i></b></span>
		<div style="padding-left:0.9375rem; padding-top:0.625rem; line-height: 1.9;">
			<div><b>&#8211; <a href="https://www.codeindotnet.com/remove-spaces-from-input-jquery-validation/">Removing Spaces Validation from Input Field via jQuery</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/difference-between-window-location-href-and-window-location-replace-and-window-location-assign-in-javascript/">Difference between window.location.href, window.location.replace, and window.location.assign in JavaScript</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/get-letters-alphabet-array-javascript/">Get Letters Alphabet Array &#8211; Javascript (JS)</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/read-html-tags-from-url-as-text-in-javascript/">Read HTML Tags from URL as text file and insert them into an existing element &#8211; Javascript</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/read-text-files-from-url-javascript-jquery/">Different Ways to Read Text Files from URLs using JavaScript and jQuery</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/check-ckeditor-version-in-javascript/">Check CKEditor Version in JavaScript</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/how-to-check-if-an-element-is-hidden-in-jquery/">How to check if an element is hidden in jQuery?</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/find-if-element-is-hidden-visible-javascript/">Javascript: find out if Element is hidden or visible</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/6-ways-to-redirect-to-another-page-javascript/">6 ways to redirect to another page in JavaScript</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/show-javascript-popup-in-page-using-html-div-element-css/">Show JavaScript Popup in a webpage using Div Elements &#038; CSS</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/find-public-ip-address-via-javascript/">Easy way to find Public IP Address: Javascript Code</a></b></div>

		</div>
	</div>
</div>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to check if an element is hidden in jQuery?</title>
		<link>https://www.codeindotnet.com/how-to-check-if-an-element-is-hidden-in-jquery/</link>
					<comments>https://www.codeindotnet.com/how-to-check-if-an-element-is-hidden-in-jquery/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 30 Jul 2023 14:58:27 +0000</pubDate>
				<category><![CDATA[JavaScript Examples]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=4230</guid>

					<description><![CDATA[In jQuery, you can use the :hidden selector to check if an element is hidden. This selector selects all elements that are hidden, either by using the CSS display property with a value of &#8220;none&#8221;, or by setting the type attribute of an input element to &#8220;hidden&#8221;. Check if an element is visible or not [&#8230;]]]></description>
										<content:encoded><![CDATA[
<br>



<p>In jQuery, you can use the <span class="spanHT">:hidden</span> selector to check if an element is hidden. This selector selects all elements that are hidden, either by using the CSS <span class="spanHT">display</span> property with a value of &#8220;none&#8221;, or by setting the <span class="spanHT">type</span> attribute of an input element to &#8220;hidden&#8221;.</p>



<br>



<h2 class="h2Cust1"><b>Check if an element is visible or not in JQuery</b></h2>



<p>To check if an element is hidden using jQuery, you can use the <code>is()</code> method in combination with the <code>:hidden</code> selector. Here&#8217;s an example:</p>



<div><b><i>Code snippet:</i></b></div>



<pre class="pchl"><code>
<span class="key">if</span> ($('#myElement').is(':hidden')) {
  <span class="com">// Element is hidden</span>
  console.log('Element <span class="key">is</span> hidden.');
} <span class="key">else</span> {
  <span class="com">// Element is visible</span>
  console.log('Element <span class="key">is</span> visible.');
} 

</code></pre>



<p>In the above example, <span class="spanHT">#myElement</span> is the selector for the element you want to check. If the element is hidden, the condition <span class="spanHT">$(&#8216;#myElement&#8217;).is(&#8216;:hidden&#8217;)</span> will evaluate to <span class="spanHT">true</span>, and the code inside the <span class="spanHT">if</span> block will be executed. If the element is visible, the code inside the <span class="spanHT">else</span> block will be executed.</p>



<p>You can replace <span class="spanHT">#myElement</span> with the appropriate selector for your element. It could be an ID, a class, or any other valid CSS selector that targets the element you want to check.</p>



<br>



<div style="padding: 0.625rem 1.25rem 1.25rem 1.25rem; box-shadow: 0.0625rem 0.0625rem 0.9375rem 0rem lightgrey; margin-bottom: 1.25rem; border-radius: 0.625rem;">
	<div><span style="border-bottom: 0.0625rem solid #cd5c5c; color:#cd5c5c;"><b><i>popular readings:</i></b></span>
		<div style="padding-left:0.9375rem; padding-top:0.625rem; line-height: 1.9;">
		
<div><b>&#8211; <a href="https://www.codeindotnet.com/how-to-check-if-an-element-is-hidden-in-jquery/">How to check if an element is hidden in jQuery?</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/find-if-element-is-hidden-visible-javascript/">Javascript: find out if Element is hidden or visible</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/6-ways-to-redirect-to-another-page-javascript/">6 ways to redirect to another page in JavaScript</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/show-javascript-popup-in-page-using-html-div-element-css/">Show JavaScript Popup in a webpage using Div Elements &#038; CSS</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/find-public-ip-address-via-javascript/">Easy way to find Public IP Address: Javascript Code</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/difference-between-innertext-and-innerhtml/">innerText and innerHTML: Understand the Difference</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/create-image-tag-after-countdown-timer-finishes-javascript/">Display an Image tag after countdown timer finishes JavaScript</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/dynamically-add-anchor-tag-in-div-html-javascript/">Dynamically generate anchor tag in div HTML javascript</a></b></div>


<div><b>&#8211; <a href="https://www.codeindotnet.com/difference-between-window-location-href-and-window-location-replace-and-window-location-assign-in-javascript/">Difference between window.location.href, window.location.replace, and window.location.assign in JavaScript</a></b></div>
	
		</div>
	</div>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/how-to-check-if-an-element-is-hidden-in-jquery/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Javascript: find out if Element is hidden or visible</title>
		<link>https://www.codeindotnet.com/find-if-element-is-hidden-visible-javascript/</link>
					<comments>https://www.codeindotnet.com/find-if-element-is-hidden-visible-javascript/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sun, 30 Jul 2023 14:56:24 +0000</pubDate>
				<category><![CDATA[JavaScript Examples]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=4209</guid>

					<description><![CDATA[How to Determine Element Visibility in JavaScript In web development, there are times when you need to determine if an element is hidden or visible. Whether it&#8217;s for enhancing user experience or implementing certain functionalities, having the ability to check the visibility status of an element is crucial. Let&#8217;s explore how to accomplish this task [&#8230;]]]></description>
										<content:encoded><![CDATA[
<br>



<h2 class="wp-block-heading has-text-align-center"><strong>How to Determine Element Visibility in JavaScript</strong></h2>



<p>In web development, there are times when you need to determine if an element is hidden or visible. Whether it&#8217;s for enhancing user experience or implementing certain functionalities, having the ability to check the visibility status of an element is crucial. Let&#8217;s explore how to accomplish this task in pure JavaScript.</p>



<br>



<h2 class="h2Cust1"><b>Checking Element Visibility in JavaScript</b></h2>



<p>In JavaScript, without relying on external libraries like <a href="https://www.codeindotnet.com/how-to-check-if-an-element-is-hidden-in-jquery/" data-type="URL" data-id="https://www.codeindotnet.com/how-to-check-if-an-element-is-hidden-in-jquery/">jQuery</a>, you can examine the CSS properties of an element to determine its visibility. Here&#8217;s a simple approach to achieve this:</p>



<div><b><i>Code snippet:</i></b></div>



<pre class="pchl" style="border:0 !important;padding-left: 15px;"><code><span class="key">
var</span> element = document.getElementById(<span class="str">'myElement'</span>);

<span class="key">if</span> (element.offsetParent === <span class="key">null</span> || element.style.display === <span class="str">'none'</span>) {
  <span class="com">// Element is hidden</span>
  console.log('Element <span class="key">is</span> hidden.');
} <span class="key">else</span> {
  <span class="com">// Element is visible</span>
  console.log('Element <span class="key">is</span> visible.');
} 

</code></pre>



<p>In the above code snippet, we first retrieve the element using its ID with <span class="spanHT">getElementById(&#8216;myElement&#8217;)</span>. Then, we evaluate two conditions. <br><strong>The first condition</strong>, <span class="spanHT">element.offsetParent === null</span>, checks if the element has an offset parent. If it doesn&#8217;t, it implies that the element is hidden. <br><strong>The second condition</strong>, <span class="spanHT">element.style.display === &#8216;none&#8217;</span>, verifies if the element&#8217;s <span class="spanHT">display</span> property is explicitly set to <span class="spanHT">&#8216;none&#8217;</span>, indicating that it is hidden. By combining these conditions, we can accurately determine the visibility status of the element.</p>



<p>Practical Usage and Customization: The ability to check element visibility opens up a range of possibilities for web developers. You can utilize this technique to implement conditional behaviors, dynamically adjust layouts, or enhance accessibility.</p>



<br>



<div><b><i>Full HTML code with Javascript &#8211; sample.</i></b></div>



<pre class="pchl"><code>
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Check Element Visibility&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

  &lt;h1 id=<span class="str">"myHeading"</span>&gt;Hello, World!&lt;/h1&gt;

  &lt;button onclick=<span class="str">"checkVisibility()"</span>&gt;Check Visibility&lt;/button&gt;

  &lt;script&gt;
    function checkVisibility() {
      <span class="key">var</span> element = document.getElementById(<span class="str">'myHeading'</span>);

      <span class="key">if</span> (element.offsetParent === <span class="key">null</span> || element.style.display === <span class="str">'none'</span>) {
        <span class="com">// Element is hidden</span>
        console.log('Element <span class="key">is</span> hidden.');
      } <span class="key">else</span> {
        <span class="com">// Element is visible</span>
        console.log('Element <span class="key">is</span> visible.');
      }
    }
  &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt; 

</code></pre>



<br>



<p>Additionally, you can modify the code snippet to suit your specific needs. For instance, instead of using <span class="spanHT">getElementById</span>, you can also use other methods like <span class="spanHT">querySelector</span> or <span class="spanHT">getElementsByClassName</span> to select the target element. This flexibility allows you to adapt the code according to your project requirements and desired element selection criteria.</p>



<br>



<div style="padding: 0.625rem 1.25rem 1.25rem 1.25rem; box-shadow: 0.0625rem 0.0625rem 0.9375rem 0rem lightgrey; margin-bottom: 1.25rem; border-radius: 0.625rem;">
	<div><span style="border-bottom: 0.0625rem solid #cd5c5c; color:#cd5c5c;"><b><i>jquery code: </i></b></span> <b><a href="https://www.codeindotnet.com/how-to-check-if-an-element-is-hidden-in-jquery/">How to check if an element is hidden in jQuery?</a></b>
		
	</div>
</div>



<br>



<div style="padding: 0.625rem 1.25rem 1.25rem 1.25rem; box-shadow: 0.0625rem 0.0625rem 0.9375rem 0rem lightgrey; margin-bottom: 1.25rem; border-radius: 0.625rem;">
	<div><span style="border-bottom: 0.0625rem solid #cd5c5c; color:#cd5c5c;"><b><i>popular readings:</i></b></span>
		<div style="padding-left:0.9375rem; padding-top:0.625rem; line-height: 1.9;">
			<div><b>&#8211; <a href="https://www.codeindotnet.com/6-ways-to-redirect-to-another-page-javascript/">6 ways to redirect to another page in JavaScript</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/show-javascript-popup-in-page-using-html-div-element-css/">Show JavaScript Popup in a webpage using Div Elements &amp; CSS</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/find-public-ip-address-via-javascript/">Easy way to find Public IP Address: Javascript Code</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/difference-between-innertext-and-innerhtml/">innerText and innerHTML: Understand the Difference</a></b></div><div><b>&#8211; <a href="https://www.codeindotnet.com/create-image-tag-after-countdown-timer-finishes-javascript/">Display an Image tag after countdown timer finishes JavaScript</a></b></div>
<div><b>&#8211; <a href="https://www.codeindotnet.com/difference-between-window-location-href-and-window-location-replace-and-window-location-assign-in-javascript/">Difference between window.location.href, window.location.replace, and window.location.assign in JavaScript</a></b></div>

		</div>
	</div>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/find-if-element-is-hidden-visible-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>6 ways to redirect to another page in JavaScript</title>
		<link>https://www.codeindotnet.com/6-ways-to-redirect-to-another-page-javascript/</link>
					<comments>https://www.codeindotnet.com/6-ways-to-redirect-to-another-page-javascript/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 01 Jul 2023 06:40:13 +0000</pubDate>
				<category><![CDATA[JavaScript Examples]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=4098</guid>

					<description><![CDATA[There are several ways to redirect to another page in JavaScript, these methods will change the current page&#8217;s URL and redirect the user to the specified URL. You can provide an absolute URL (starting with &#8220;http://&#8221; or &#8220;https://&#8221;) or a relative URL (relative to the current page&#8217;s location). Here are six common methods explained below [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInHoriAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>



<br>



<p>There are several ways to redirect to another page in JavaScript, these methods will change the current page&#8217;s URL and redirect the user to the specified URL. You can provide an absolute URL (starting with &#8220;http://&#8221; or &#8220;https://&#8221;) or a relative URL (relative to the current page&#8217;s location). Here are six common methods explained below along with examples:</p>



<br>



<h2 class="h2Cust2">1. Redirect using the <span style="border-bottom: 1px solid #d3d3d3;">window.location.href</span> property</h2>



<p>window.location.href is used to get or set the complete URL of the current page. <br>It is commonly used to redirect the browser to a new page by setting it to a new URL.</p>



<pre class="pchl" style="border:0 !important;padding-left: 15px;"><code><span class="com">// Redirect to a specific URL</span>
window.location.href = <span class="str">"https://www.codeindotnet.com"</span>;

<span class="com">// Redirect to a relative URL</span>
window.location.href = <span class="str">"/page2.html"</span>; </code></pre>



<br><br>



<h2 class="h2Cust2">2. Redirect using the <span style="border-bottom: 1px solid #d3d3d3;">window.location.replace()</span> method</h2>



<p>window.location.replace() is used to replace the current page in the browser&#8217;s history with a new page. <br>It is typically used for redirects when you don&#8217;t want the user to navigate back to the original page using the browser&#8217;s back button.</p>



<pre class="pchl" style="border:0 !important;padding-left: 15px;"><code><span class="com">// Redirect to a specific URL</span>
window.location.replace(<span class="str">"https://www.codeindotnet.com"</span>);

<span class="com">// Redirect to a relative URL</span>
window.location.replace(<span class="str">"/page2.html"</span>); </code></pre>



<br><br>



<h2 class="h2Cust2">3. Redirect using the <span style="border-bottom: 1px solid #d3d3d3;">window.location.assign()</span> method</h2>



<p>window.location.assign() is used to load a new URL. <br>It is similar to window.location.href in that it can be used for redirection. However, unlike replace(), it adds the new URL to the browser&#8217;s history, allowing the user to navigate back to the original page using the back button.</p>



<pre class="pchl" style="border:0 !important;padding-left: 15px;"><code><span class="com">// Redirect to a specific URL</span>
window.location.assign(<span class="str">"https://www.codeindotnet.com"</span>);

<span class="com">// Redirect to a relative URL</span>
window.location.assign(<span class="str">"/page2.html"</span>); </code></pre>



<br><br>



<h2 class="h2Cust2">4. Redirect using the <span style="border-bottom: 1px solid #d3d3d3;">window.location</span> object</h2>



<p>window.location is an object that provides information and methods related to the current URL of the page. <br>It contains properties such as href, host, pathname, and methods such as reload() and replace().</p>



<pre class="pchl" style="border:0 !important;padding-left: 15px;"><code><span class="com">// Redirect to a specific URL</span>
window.location = <span class="str">"https://www.codeindotnet.com"</span>;

<span class="com">// Redirect to a relative URL</span>
window.location = <span class="str">"/page2.html"</span>; </code></pre>



<br><br>



<h2 class="h2Cust2">5. Redirect using the <span style="border-bottom: 1px solid #d3d3d3;">document.location.href</span> property</h2>



<p>document.location.href is an alternative way to access the URL of the current page. <br>It is essentially the same as window.location.href.</p>



<pre class="pchl" style="border:0 !important;padding-left: 15px;"><code><span class="com">// Redirect to a specific URL</span>
document.location.href = <span class="str">"https://www.codeindotnet.com"</span>;

<span class="com">// Redirect to a relative URL</span>
document.location.href = <span class="str">"/page2.html"</span>; </code></pre>



<br><br>



<h2 class="h2Cust2">6. Redirect using the <span style="border-bottom: 1px solid #d3d3d3;">location.replace()</span> method</h2>



<p>location.replace() is a shorthand method for window.location.replace(). <br>It is used to replace the current page in the browser&#8217;s history with a new page, similar to replace().</p>



<pre class="pchl" style="border:0 !important;padding-left: 15px;"><code><span class="com">// Redirect to a specific URL</span>
location.replace(<span class="str">"https://www.codeindotnet.com"</span>);

<span class="com">// Redirect to a relative URL</span>
location.replace(<span class="str">"/page2.html"</span>); </code></pre>



<br><br>



<h2 class="h2Cust2"><strong>When to use?</strong></h2>



<div><b>In terms of the best scenario for each:</b></div>



<ul class="ul1">

<li style="padding-bottom: 0.625rem;">Use <span class="spanHT">window.location.href</span> or <span class="spanHT">document.location.href</span> when you want to redirect the user to a new page and you want the new URL to be added to the browser&#8217;s history.</li>

<li style="padding-bottom: 0.625rem;">Use <span class="spanHT">window.location.replace()</span> or <span class="spanHT">location.replace()</span> when you want to redirect the user to a new page and you don&#8217;t want the original page to be stored in the browser&#8217;s history.</li>

<li style="padding-bottom: 0.625rem;">Use <span class="spanHT">window.location.assign()</span> when you want to redirect the user to a new page and you want the new URL to be added to the browser&#8217;s history, allowing the user to navigate back to the original page.</li>

<li style="padding-bottom: 0.625rem;">Use the <span class="spanHT">window.location</span> object when you need to access or modify properties of the current URL, such as getting the current hostname or pathname.</li>

</ul>



<p>The choice of which method to use depends on the specific requirements of your application and how you want the redirection to behave.</p>



<br>



<div style="padding: 0.625rem 1.25rem 1.25rem 1.25rem; box-shadow: 0.0625rem 0.0625rem 0.9375rem 0rem lightgrey; margin-bottom: 1.25rem; border-radius: 0.625rem;">
	<div><span style="border-bottom: 0.0625rem solid #cd5c5c; color:#cd5c5c;"><b><i>Read also:</i></b></span>
		<div style="padding-left:0.9375rem; padding-top:0.625rem; line-height: 1.9;">
			<div><b><a href="/difference-between-window-location-href-window-and-location-replace-and-window-location-assign-in-javascript/">Difference between window.location.href, window.location.replace, and window.location.assign in JavaScript</a></b></div>
		</div>
	</div>
</div>



<br>



<div id="PageInAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/6-ways-to-redirect-to-another-page-javascript/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Show JavaScript Popup in a webpage using Div Elements &#038; CSS</title>
		<link>https://www.codeindotnet.com/show-javascript-popup-in-page-using-html-div-element-css/</link>
					<comments>https://www.codeindotnet.com/show-javascript-popup-in-page-using-html-div-element-css/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 05 Jun 2023 08:44:52 +0000</pubDate>
				<category><![CDATA[JavaScript Examples]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=3909</guid>

					<description><![CDATA[Popups are a common way to display additional information or request user input in a web application. Placing the popup in the center of the web page ensures that it is easily visible and accessible to the user. In this article, we will explore how to show a popup in the center of the page [&#8230;]]]></description>
										<content:encoded><![CDATA[
<br>



<p>Popups are a common way to display additional information or request user input in a web application. Placing the popup in the center of the web page ensures that it is easily visible and accessible to the user. In this article, we will explore how to show a popup in the center of the page using HTML Div tags, CSS (styles) &amp; JavaScript, along with a code sample to help you implement this functionality in your own projects.</p>



<br><br><h2 class="h2Cust1">Demo -Show popup in the center of the web page</h2><br>



<div><b><i>Sample video &#8211; Show Popup</i></b></div>



<figure class="wp-block-video"><video autoplay controls loop src="https://unifydetails.com/v/popup-video-sample.mp4"></video></figure>



<br><br>



<h2 class="wp-block-heading has-text-align-center"><strong>Test Yourself &#8211; Manually</strong></h2>



<br><div>Click on the &#8220;Show popup&#8221; button to display child window.</div><br>



<script>
window.addEventListener('load',function(){
	// Get the popup and overlay elements
	var popup = document.getElementById("MyPopup");
	var overlay = document.getElementById('ppOverlay');

	// Get the close button element
	var close = document.getElementById('btnpopclose');

	// Function to display the popup
	document.getElementById("showpopup").addEventListener("click",
	function showpopup() { 
		popup.style.display = 'block';
		overlay.style.display = 'block';

		// Add event listeners to close the popup
		document.addEventListener('keydown', closePopupOnEscape);
		overlay.addEventListener('click', closePopup);
		close.addEventListener('click', closePopup);
	});

	// Function to close the popup
	function closePopup() {
		popup.style.display = 'none';
		overlay.style.display = 'none';

		// Remove event listeners during closing the popup
		document.removeEventListener('keydown', closePopupOnEscape);
		overlay.removeEventListener('click', closePopup);
		close.removeEventListener('click', closePopup);
	}

	// Function to close the popup when the escape key is pressed
	function closePopupOnEscape(event) {
		if (event.keyCode === 27) {
			closePopup();
		}
	}
	
});
</script>
<style>
.popup {
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 50%;
	background-color: #fff;
	border: 0.0625rem solid #d3d3d3;
	box-shadow: 0 0 0.625rem #e5e2e2;
	border-radius: 0.625rem;
	z-index: 999;
	display: none;
	height:300px;
}

@media screen and (max-width: 700px) {
    .popup {
        width: 90%;
    }
}

.popup-overlay {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: #fff0;
	z-index: 998;
	display: none;
}
.popup-header {
	background-color: #f3f3f3;
	padding: 0.625rem;			
}
.popup-close {
	font-size: 1.25rem;
	font-weight: bold;
	padding: 0.3125rem 0.625rem;
	border-radius: 0.3125rem;
	background-color: #f00;
	color: #fff;
	border: none;
	float: right;
	margin: -0.3125rem;
}

#showpopup {
	background: #db0000;
	border: 0;
	padding: 0.625rem 1.5625rem 0.3125rem;
	border-radius: 0.9375rem 0.9375rem;
	font-size: 1rem;
	font-weight: bold;
	outline: none;
	cursor: pointer;
	vertical-align: top;
    float: right;
    color:#fff;
}
#showpopup:hover {
	box-shadow: 0 0 5px gray;
}


.divpage{
    padding: 5px;
    border: 1px solid grey;
    position: relative;
    height: 200px;
    box-shadow: 0 0 5px;
}
</style>

<div class="divpage">
<button id="showpopup">Show Popup</button>
<center><div style="font-size:26;"><b>Main Page</b></div></center>
<div>
<br><br><center>Click on the <b>Show popup</b> button to show popup window.</center><br>Main page contents&#8230;..
</div>


<div id="ppOverlay" class="popup-overlay"></div>

<div id="MyPopup" class="popup">
	<div class="popup-header">
		<span style="font-weight:bold; padding-right:5px; padding-left:15px;">Popup Title: </span>
		
		<button id="btnpopclose" class="popup-close">×</button>
	</div>
	<div style="padding:15px;">
		<center><h2>Popup Heading</h2></center>
		<br>
		<div>
			This is a sample text&#8230;<br> second line
		</div>
	</div>
</div>
</div>



<br><br><br><br>



<h2 class="h2Cust1">HTML, CSS &amp; Javascript Code &#8211; Show popup</h2>



<p>Simply copy &amp; paste the below HTML code into a text file and save it as a &#8220;.html&#8221; file. Open it in a browser to test the HTML code.</p>



<pre style="border-bottom:0 !important;">
<span style="color:blue;">&lt;html&gt;
&lt;head&gt;
&lt;script&gt;</span>
window.addEventListener('load',function(){
	<span style="color:#a52a2a; font-weight:bold;">// Get the popup and overlay elements</span>
	var popup = document.getElementById("MyPopup");
	var overlay = document.getElementById('ppOverlay');

	<span style="color:#a52a2a; font-weight:bold;">// Get the close button element</span>
	var close = document.getElementById('btnpopclose');

	<span style="color:#a52a2a; font-weight:bold;">// add javascript onclick event and function to display the popup</span>
	document.getElementById("showpopup").addEventListener("click",
	function showpopup() { 
		popup.style.display = 'block';
		overlay.style.display = 'block';

		<span style="color:#a52a2a; font-weight:bold;">// Add event listeners to close the popup</span>
		document.addEventListener('keydown', closePopupOnEscape);
		overlay.addEventListener('click', closePopup);
		close.addEventListener('click', closePopup);
	});

	<span style="color:#a52a2a; font-weight:bold;">// Function to close the popup</span>
	function closePopup() {
		popup.style.display = 'none';
		overlay.style.display = 'none';

		<span style="color:#a52a2a; font-weight:bold;">// Remove event listeners during closing the popup</span>
		document.removeEventListener('keydown', closePopupOnEscape);
		overlay.removeEventListener('click', closePopup);
		close.removeEventListener('click', closePopup);
	}

	<span style="color:#a52a2a; font-weight:bold;">// Function to close the popup when the escape key is pressed</span>
	function closePopupOnEscape(event) {
		if (event.keyCode === 27) {
			closePopup();
		}
	}
	
});
<span style="color:blue;">&lt;/script&gt;</span></pre>



<pre style="border-top:0 !important;">
<span style="color:blue;">&lt;style&gt;</span>
.popup {
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 50%;
	background-color: #fff;
	border: 0.0625rem solid #d3d3d3;
	box-shadow: 0 0 0.625rem #e5e2e2;
	border-radius: 0.625rem;
	z-index: 999;
	display: none;
	height:400px;
}

@media screen and (max-width: 700px) {
    .popup {
        width: 90%;
    }
}

.popup-overlay {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: #fff0;
	z-index: 998;
	display: none;
}
.popup-header {
	background-color: #f3f3f3;
	padding: 0.625rem;			
}
.popup-close {
	font-size: 1.25rem;
	font-weight: bold;
	padding: 0.3125rem 0.625rem;
	border-radius: 0.3125rem;
	background-color: #f00;
	color: #fff;
	border: none;
	float: right;
	margin: -0.3125rem;
}

#showpopup {
	background: #db0000;
	border: 0;
	padding: 0.625rem 1.5625rem 0.3125rem;
	border-radius: 0.9375rem 0.9375rem;
	font-size: 1rem;
	font-weight: bold;
	outline: none;
	cursor: pointer;
	vertical-align: top;
    float: right;
    color:#fff;
}
#showpopup:hover {
	box-shadow: 0 0 5px gray;
}

<span style="color:blue;">&lt;/style&gt;
&lt;/head&gt;</span>

<span style="color:blue;">&lt;body&gt;</span>
<span style="color:#a52a2a; font-weight:bold;">// popup button on the main page.</span>
&lt;button id="showpopup"&gt;Show Popup&lt;/button&gt;

<span style="color:#a52a2a; font-weight:bold;">// popup child window section. This will be displayed when "Show popup" button is clicked.</span>
&lt;div id="ppOverlay" class="popup-overlay"&gt;&lt;/div&gt;

&lt;div id="MyPopup" class="popup"&gt;
	&lt;div class="popup-header"&gt;
		&lt;span style="font-weight:bold; padding-right:5px; padding-left:15px;"&gt;This is my popup heading: &lt;/span&gt;
		
		&lt;button id="btnpopclose" class="popup-close"&gt;×&lt;/button&gt;
	&lt;/div&gt;
	&lt;div style="padding:15px;"&gt;
		&lt;h2&gt;Popup Heading&lt;/h2&gt;
		&lt;br&gt;
		&lt;div&gt;
			This is a sample text...&lt;br&gt; second line
		&lt;/div&gt;
	&lt;/div&gt;
&lt;/div&gt;
<span style="color:blue;">&lt;/body&gt;

&lt;/html&gt;</span>
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/show-javascript-popup-in-page-using-html-div-element-css/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		<enclosure url="https://unifydetails.com/v/popup-video-sample.mp4" length="102838" type="video/mp4" />

			</item>
		<item>
		<title>Easy way to find Public IP Address: Javascript Code</title>
		<link>https://www.codeindotnet.com/find-public-ip-address-via-javascript/</link>
					<comments>https://www.codeindotnet.com/find-public-ip-address-via-javascript/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 01 Jun 2023 16:07:10 +0000</pubDate>
				<category><![CDATA[JavaScript Examples]]></category>
		<category><![CDATA[Internet Protocol address]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=2343</guid>

					<description><![CDATA[What is my Internet IP Address? Live example Finding your IP address&#8230; see the HTML &#38; JS implementation, below IP Address: HTML and Javascript Code Finding your public IP address is not a straightforward approach. If you just need the user or visitor&#8217;s public IP address after the page load to log or perform any [&#8230;]]]></description>
										<content:encoded><![CDATA[
<br>
<center>
<h2>What is my Internet IP Address?</h2>
<h3 style="color:#df1a1a;"><b><u>Live example</u></b></h3>
<br>
<div id="ipaddress">Finding your IP address&#8230;</div>
<br>
<div>see the HTML &amp; JS implementation, below</div>
</center>



<script>
window.addEventListener('load', async function(){
try{
    const response = await fetch("https://api.ipify.org/?format=json");
    var data = await response.json();
document.getElementById("ipaddress").innerHTML = "<span style='font-size:26px; font-weight:bold'>" + data.ip + "</span><br>Your IP address";
}
catch(err){
document.getElementById("ipaddress").innerText = "Timeout, Please refresh and try again.";
}
    });
  </script>



<br><br>



<h2 class="h2Cust1"><strong>IP Address: HTML and Javascript Code</strong></h2>



<p>Finding your public IP address is not a straightforward approach. If you just need the user or visitor&#8217;s public IP address after the page load to log or perform any operation then by utilizing a simple JavaScript code snippet you can retrieve the public IP address without relying on paid services.</p>



<br>



<h2 class="wp-block-heading">Use Free API &#8211; Unlimited request</h2>



<div>You can use the free API provided by &#8216;ipify.org&#8217; which is absolutely free. </div>



<ul style="padding:0.3125rem 1.5625rem; margin-bottom: 0.3125rem;">
<li>without any limit, (even millions of requests per minute)</li>

<li>Opensource (<a href="https://github.com/rdegges/ipify-api" target="_blank" rel="noreferrer noopener">GitHub repository</a>)</li>

<li>works with both IPv4 and IPv6 addresses</li>
</ul>



<p>for more details, visit <a href="https://www.ipify.org/" target="_blank" rel="noopener"><strong>https://www.ipify.org/</strong></a></p>



<br>



<h2 class="wp-block-heading">Calling ipify API</h2>



<div>Open browser and try any API on the address bar</div>



<pre class="wp-block-code"><code>1) https://api.ipify.org/
output: 27.4.142.189

(or)

2)https://api.ipify.org/?format=json
output: {"ip":"27.4.142.189"}

(or)

3) https://api.ipify.org/?format=json&amp;callback=getIP
output: {"ip":"27.4.142.189"}</code></pre>



<br><br>



<h2 class="wp-block-heading"><strong>How to Implement &#8211; HTML &amp; JS Script &#8211; Samples</strong></h2>



<p>Simply use this HTML and javascript to get the public IP address. <br>See the live example above (<strong>used the same JS code</strong>)</p>



<h3 class="wp-block-heading" id="sample1"><strong><em><span style="text-decoration: underline;">Sample code 1:</span></em></strong></h3>



<pre class="wp-block-code"><code>&lt;html&gt;
&lt;br&gt;
&lt;center&gt;
&lt;div&gt;
&lt;h2&gt;What is my Internet IP Address?&lt;/h2&gt;
&lt;/div&gt;
&lt;br&gt;
&lt;div id="ipaddress"&gt;Finding your IP address...&lt;/div&gt;
&lt;/center&gt;
&lt;/html&gt;</code></pre>



<pre class="wp-block-code"><code>&lt;script&gt;
	window.addEventListener('load', async function(){
		<b>try</b>{
			const response = <b>await</b> fetch("https://api.ipify.org/?format=json");
			var data = <b>await</b> response.json();
			document.getElementById("ipaddress").innerHTML = "&lt;span style='font-size:26px; font-weight:bold'&gt;" + data.ip + "&lt;/span&gt;&lt;br&gt;Your IP address";
		}
		<b>catch(err)</b>{
			document.getElementById("ipaddress").innerText = "Timeout, Please refresh and try again.";
		}
	});
&lt;/script&gt;</code></pre>



<br><br>



<h3 class="wp-block-heading"><strong><span style="text-decoration: underline;"><em>Sample code </em>2:</span></strong></h3>



<pre class="wp-block-code"><code>&lt;html&gt;
&lt;br&gt;
&lt;center&gt;
&lt;div&gt;
&lt;h2&gt;What is my Internet IP Address?&lt;/h2&gt;
&lt;/div&gt;
&lt;br&gt;
&lt;div id="ipaddress"&gt;Finding your IP address...&lt;/div&gt;
&lt;/center&gt;
&lt;/html&gt;</code></pre>



<pre class="wp-block-code"><code>&lt;script&gt;
  function getIP(json) {
    document.getElementById("ipaddress").innerHTML = "&lt;span style='font-size:26px; font-weight:bold'&gt;" + json.ip + "&lt;/span&gt;&lt;br&gt;Your IP address";
  }
&lt;/script&gt;
&lt;script src="https://api.ipify.org?format=jsonp&amp;amp;callback=getIP"&gt;&lt;/script&gt;</code></pre>



<br><br>



<div class="note">
<div style="color:#00008b; font-weight:bold; border-bottom:0.125rem #00008b solid; font-style:italic;">Note:</div>
<div class="notepoints" style="padding-top:0.375rem">Please use <span class="spanHT">try catch &amp; await</span>. <br>In rare situation, you might get <b>timeout</b> error because of response delay from API. In such case, use await keyword with try catch block.
<br>See &#8220;<a href="#sample1" data-type="internal" data-id="#sample1"><b>Sample code 1</b></a> implementation, above</div>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/find-public-ip-address-via-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
