'Problem with the function of pressing a button in JavaScript

I set a button with a function and it gives me an error:

end1.html: "20 Uncaught ReferenceError: reload is not defined at HTMLButtonElement.onclick"

How do I fix this?

<body>
    <button id="Reload" type="button" class="myButton" onclick="reload()"> reload </button>

<script>
function reload(){
    if(localStorage.a==6){
        Location.href="page2.html";
    }
    if(localStorage.a==8){
        Location.href="page3.html";
    }
    if(localStorage.a==10){
        Location.href="page4.html";
    } 
 } 
</script>
</body>


Solution 1:[1]

A fix is to use the built-in addEventListener() function in JavaScript, instead of using the onclick attribute in HTML.

To use this feature, you can delete the onclick attribute on your <button> element in your HTML, so that it will look like this.

<button id="Reload" type="button" class="myButton">Reload</button>

Then, you can add the following function in your JavaScript. Add the following lines below your reload() function.

const reloadButton = document.querySelector("#Reload"); // Get the button from the DOM

function reload() {
  // Function code...
}

reloadButton.addEventListener("click", reload); // Alternative to 'onclick'

The listener will wait for a click event, and when it occurs, it will run the reload() function (without a ReferenceError).


Also, in your reload() function, you need to change Location to location. This is because JavaScript is case-sensitive, and it will throw an error if you leave Location as-is.

// Before
Location.href;

// After
location.href;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1