index.html file path: /Users/nixon/Documents/Website Development/Pers Website/index.html
loginpage.html path: /Users/nixon/Documents/Website Development/Pers Website/loginpage.html
let loginButton = document.querySelector("#login") loginButton.addEventListener('click', reDirectingLoginPage); function reDirectingLoginPage() { window.replace("/Users/nixon/Documents/Website Development/Pers Website/index.html") }
—UPDATE AS OF 08/08/2020—
Tried updating the code to this and it still didn’t work. HTML:
button onclick="goToURL" id="login" type="button" class="btn btn-lg btn-dark">Login</button">
JS:
function goToURL() { window.open("Users/nixon/Documents/Website Development/Pers Website/loginpage.html") }
No errors in console: https://gyazo.com/29a2084c082f66f943795ecfef3b3909
Advertisement
Answer
[1.0] Your onclick needs parenthesis.
[1.1] You could do an event listener instead. Doing it this way, you’ll omit the parenthesis
[1.2] If you aren’t doing anything else other than loading a new page with the javascript, you don’t need javascript for that. anchor elements are meant for navigating to webpages.
[1.3] replace() is a part of the location object. Not the window. Instead of window.replace()
it should be window.location.replace()
[1.4] I had previously mentioned replace
, but noticed that this keeps you from being able to use the back button. If you use assign
instead, the back button will work normally.
let loginButton1 = document.querySelector("#login1"); let loginButton2 = document.querySelector("#login2"); loginButton2.addEventListener('click', reDirectingLoginPage); function reDirectingLoginPage() { // [1.3] and [1.4] // window.location.replace("http://example.com"); window.location.assign("http://example.com"); alert("these url assignments aren't working stackoverflow code snippets. This alert proves it's running. Take these to your project and they should work."); }
<!-- [1.0] --> <button id="login1" onclick="reDirectingLoginPage()">Login1</button> <!-- [1.1] --> <button id="login2">Login2</button> <!-- [1.2] --> <a href="http://example.com">Login3</a>