JavaScript load a page on button click

JavascriptButtonLoad

Javascript Problem Overview


I am trying to do a very simple task here, I would like to be able to click a button on a page and have it take me to another page. I have tried window.location.href, and a bunch of other things and it does nothing. I have tried different platforms and different browsers, all with the same result.

I know that it can call a function but I just cannot get the new page to load. Also this is all in my local file system and both pages live at the same level (but I have also tried to load an external page like www.apple.com).

Any thoughts?

Thanks Patrick

Javascript Solutions


Solution 1 - Javascript

Simple code to redirect page

<!-- html button designing and calling the event in javascript -->
<input id="btntest" type="button" value="Check" 
       onclick="window.location.href = 'http://www.google.com'" />

Solution 2 - Javascript

Don't abuse form elements where <a> elements will suffice.

<style>
    /* or put this in your stylesheet */

    .button {
        display: inline-block;
        padding: 3px 5px;
        border: 1px solid #000;
        background: #eee;
    }

</style>

<!-- instead of abusing a button or input element -->
<a href="url" class="button">text</a>

Solution 3 - Javascript

Just window.location = "http://wherever.you.wanna.go.com/", or, for local links, window.location = "my_relative_link.html".

You can try it by typing it into your address bar as well, e.g. javascript: window.location = "http://www.google.com/".

Also note that the protocol part of the URL (http://) is not optional for absolute links; omitting it will make javascript assume a relative link.

Solution 4 - Javascript

The answers here work to open the page in the same browser window/tab.

However, I wanted the page to open in a new window/tab when they click a button. (tab/window decision depends on the user's browser setting)

So here is how it worked to open the page in new tab/window:

<button type="button" onclick="window.open('http://www.example.com/', '_blank');">View Example Page</button>

It doesn't have to be a button, you can use anywhere. Notice the _blank that is used to open in new tab/window.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPatrickView Question on Stackoverflow
Solution 1 - JavascriptPranay RanaView Answer on Stackoverflow
Solution 2 - JavascriptBGerrissenView Answer on Stackoverflow
Solution 3 - JavascripttdammersView Answer on Stackoverflow
Solution 4 - JavascriptTarikView Answer on Stackoverflow