Nicely, HTTP redirection is a giant matter and completely different folks do it in another way. e.g. bloggers largely used platforms like WordPress, Blogger characteristic to redirect a web page, although this is likely to be restricted to the identical area.
On this JavaScript and jQuery tutorial, we are going to study a brand new JQuery tip to redirect a web page.
Btw, If you’re studying jQuery then I additionally counsel you make a copy of Head First jQuery, I’ve and at all times look again on this e-book each time I’m caught. It’s got some good examples, which you’ll be able to at all times refer again to.
jQuery Code to redirect a web page or URL.
Right here is the JQuery code for redirecting a web page. Since I’ve put this code on $(doc).prepared() perform, it can execute as quickly because the web page is loaded.
You possibly can even move URL on to attr() methodology, as a substitute of utilizing a variable.
JavaScript Code for redirecting a URL
It is even easier in JavaScript. You solely want to alter window.location.href property to redirect a web page. Although some folks additionally use window.location solely, which can be high quality. If you’re curious concerning the distinction between window.location and window.location.href, then you possibly can see that later one is setting href property explicitly, whereas earlier one does it implicitly. Since window.location returns an object, which by default units it is .href property.
There’s one other solution to redirect a web page utilizing JavaScript, exchange() methodology of window.location object. You possibly can move a brand new URL to interchange() methodology and it’ll simulate an HTTP redirect.
By the best way, do not forget that window.location.exchange() methodology does not put the originating web page within the session historical past, which can have an effect on the conduct of the again button. Typically, it is what you need, so use it rigorously.
HTML Instance of Redirecting a Web page or URL
Here’s a full HTML web page, which makes use of the above methodology to redirect a web page or URL. Since you possibly can solely use one methodology at a time, I’ve commented remainder of the code for redirection. You possibly can uncomment and take a look at them as properly.
That is all on tips on how to redirect a web page or URL utilizing JQuery and JavaScript. It is debatable, whether or not to caught with JavaScript or JQuery for redirection, but when I would like to decide on between each of them, I might go together with jQuery, as a result of jQuery gives cross-browser compatibility. Although window.location.href may match on all browsers, it is higher to be secure than sorry.