The onclick is not working on first click

Viewed 12161

I am working on one JavaScript project, where I need to toggle between Celsius and Fahrenheit. The HTML is here

<button onclick="toggleCF();" id="toggleCF" class="button">Toggle C/F</button>

And here is the JavaScript Function

this.toggleCF = function() {
    console.log('click');
    var fahrenheit = document.getElementById('toggleFahrenheit');
    var celsius = document.getElementById('toggleCelsius');

    if (fahrenheit.style.display === 'none') {
        fahrenheit.style.display = 'block';
        celsius.style.display = 'none';
    } else {
        fahrenheit.style.display = 'none';
        celsius.style.display = 'block';
    }
}

The CSS I used is given

.temperature-celsius {

}
.temperature-fahrenheit {
    display: none;
}

If you want to check this application live here is the link

Please click on this link to see app in running form

If you visit the above link and check, you will find that on first click the toggle didn't work. But when you click the second time then it starts working normally.

4 Answers

This often happen most of the time on your css content not being been loaded up fully i have my issue solved with the following code:

function yourFunction() {
   document.addEventListener("DOMContentLoaded", function(){
       // you works start here
   });
}

The simple solution is to use the EventListener . I had the same problem with the onclick but when using :

const myEl = document.getElementById('myBtn');
myEl.addEventListener('click', function () {

//Your code here

});

It works on first click!

Related