Onclick does not work on first click

I am working on one JavaScript project where I need to switch between degrees Celsius and Fahrenheit. 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';
    }
}

CSS i used

.temperature-celsius {

}
.temperature-fahrenheit {
    display: none;
}

If you want to check out this application live here link

Please click on this link to see the application in a running form.

If you follow the link above and check, you will find that the switch does not work the first time you click. But when you click a second time, it starts working fine.

+6
source share
3 answers

, if (fahrenheit.style.display === 'none') NULL, . "" CSS, . :

var element = document.getElementById('toggleFahrenheit'),
    style = window.getComputedStyle(element),
    top = style.getPropertyValue('top');

CSS JS JQuery, .

+1

, div toggleFahrenheit toggleCelsius style. CSS, , style .

, , . fahrenheit.style.display null, style. fahrenheit.style.display === 'none' false. else, Celsius. , , , .

, , , div- style.

, div, , Celsius, .

.

function toggle() {
  var fahrenheit = document.getElementById("fahrenheit");
  var celsius = document.getElementById("celsius");
  fahrenheit.classList.toggle('hide');
  celsius.classList.toggle('hide');
}
.hide { display: none; }
<div id="fahrenheit" class="hide">-40 F</div>
<div id="celsius">-40 C</div>
<button onclick="toggle()">Toggle</button>
Hide result

, -40 , , , (:

+3

CSS , :

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

Source: https://habr.com/ru/post/1682578/


All Articles