How to Open a Link On Button Click JavaScript

Opening a link or redirecting a user to a new page on our website using a button on click event is only possible with JavaScript.

Often we use <a> tag to redirect users on a new page or to open a new link. However, on some special occasions, we have to redirect the user on the button click event using JavaScript.

Redirect User on Click Event JavaScript

There are few methods to redirect or to open a new link on click event using JavaScript.

Method 1: Using Window.open()

This method is a straightforward approach to redirect the user to a new page.

<html>
	<head>
		<title>Redirect using window.open()</title>
	</head>
	<body>
		<p>Redirect in same page</p>
		<button onclick="window.open('https://errorsea.com','_self');">click me</button>
		<p>Open in new page</p>
		<button onclick="window.open('https://errorsea.com','_blank');">click me</button>
	</body>
</html>

Method 2: Using JavaScript

This method is quite a unique way to redirect users. This method redirects users and leaves the same expression as the user opens a link via <a> tag on the web-page.

<html>
	<head>
		<title>Redirect using JavaScript</title>
	</head>
	<body>
		<button onclick="openTab('https://errorsea.com')">Try it</button>
		<script>
		function openTab(url) {
			const link = document.createElement('a');
			link.href = url;
			link.target = '_blank';
			document.body.appendChild(link);
			link.click();
			link.remove();
		}
		</script>
	</body>
</html>

Conclusion

Redirecting users is an essential factor in maintaining the bounce rate and SEO. I hope you understand the complete methodology of redirection users using JavaScript.

Happy Scripting 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

Read previous post:
Remove On-Page Errors in PHP
How to Remove On-Page Errors in PHP

On-page errors, warnings, and notices are default in PHP for convenient debugging. However, while deploying on production it is not...

Close