.location

The .location method can be used to redirect or return information about the current location.

 

Redirect

To redirect assign the target page to the window.location() function, like so:

 

window.location = "https://www.motogp.com"; //note use of assignment, not parentheses

 

To redirect a page straight away:

<html>
	<head>
		<title>JavaScript</title>
		<script>
			window.location = "https://www.google.co.uk";
		</script>
	</head>
	<body>
	</body>
</html>

 

Or to call from a function, which could then be used in a setInterval():

<html>
	<head>
		<title>JavaScript</title>
		<script>

		function myRedirect(){
			window.location = "https://js.tech-academy.co.uk";
		}
		document.write("redirecting in 5 seconds.");
		setTimeout('myRedirect()', 5000);
		</script>
	</head>
	<body>
	</body>
</html>

 

 

Return values

.location can also be used to return values:

<html>
	<head>
		<title>JavaScript</title>
	</head>
	<body>
		<script>
			document.write(location.href + "<br>");
			document.write(location.pathname + "<br>");
			document.write(location.port + "<br>");
			document.write(location.protocol + "<br>");
		</script>
	</body>
</html>

Leave a Reply