Skip to content
Advertisement

Very Simple HTML/JavaScript Button Not Working

What should be an incredibly simple button is not working. All I want is for it to log something to the console for some testing purposes, but it refuses to work.

<button type="button" id="add-marker-button">Create Marker</button>

There’s the button in my HTML file, and below is the JavaScript that, as far as I can tell, should be working.

function AddMarker() {
    let latInput = document.getElementById("lat-input").value;
    let longInput = document.getElementById("lat-input").value;

    lat = parseInt(latInput);
    long = parseInt(longInput);

    console.log(`Lat: ${lat}, Long: ${long}`);
}
function PleaseWork(){
    console.log(`It works!`);
}

window.onload = function() {
    document.getElementById("add-marker-button").addEventListener("onclick", PleaseWork());
}

All I want is for the button to call the AddMarker function. I’ve added an even simpler function to make sure AddMarker didn’t have any issues, and it still doesn’t work. Without the window.onload my getElementById returns null, and I experimented with wrapping the entire code with the window.onload, that seemed to change nothing. Everything seems to work with inline JavaScript, but for some reason when accessing the button through the DOM, things stop working. The code below works fine.

<script>
    function buttonTest() {
        let latInput = document.getElementById("lat-input").value;
        let longInput = document.getElementById("lat-input").value;
        
        lat = parseInt(latInput);
        long = parseInt(longInput);
        
        console.log(`Lat: ${lat}, Long: ${long}`);
    }
</script>
<button onclick="buttonTest()">test</button>

This is really frustrating to me as it should be so simple. It’s probably something obvious, but I can’t figure it out for the life of me. Any help is appreciated!

Advertisement

Answer

 function AddMarker() {
    let latInput = document.getElementById("lat-input").value;
    let longInput = document.getElementById("lat-input").value;

    lat = parseInt(latInput);
    long = parseInt(longInput);

    console.log(`Lat: ${lat}, Long: ${long}`);
}
function PleaseWork(){
    alert('It Works');
    console.log(`It works!`);
}

window.onload = function() {
    document.getElementById("add-marker-button").addEventListener("click", PleaseWork);
}
 
<button type="button" id="add-marker-button">Create Marker</button>

   
 window.onload = function() {
    
       document.getElementById("add-marker-button").addEventListener("click", PleaseWork);
    
    }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement