Subaz Subaz - 22 days ago 6
Javascript Question

If.. Then in javascript

I want to change the font size of a text depending on the current font size.

Algorithm:

On clicking the text,

If font size = 35, change it to 12

else if font size = 12, change it to 35






<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>

<p id="demo" onclick="myFunction()">Click me.</p>

<script>
function myFunction() {
if (document.getElementById('demo').style.fontSize='35px') {
document.getElementById('demo').style.fontSize='12px'
} else if(document.getElementById('demo').style.fontSize='12px') {
document.getElementById('demo').style.fontSize='35x'
}

}

</script>
</body>
</html>








It changed it 12, but never changes back to 35. What did I miss here?

Answer Source

You have assignment in the if statement. You need to use not =, but == or better ===.

Also one note, if the font-size is defined in the css, it may return to you an empty string for the first time. In this case you need to use window.getComputedStyle to get the font-size.

function myFunction() {
      const element = document.getElementById('demo');
      console.log(element.style.fontSize);
      const fontSize = window.getComputedStyle(element, null).getPropertyValue('font-size');

      if (fontSize === '35px') {
        element.style.fontSize = '12px';
      } else if(fontSize === '12px') {
        element.style.fontSize = '35px';
      }
}
p#demo {
   font-size: 12px;
}
<h2>What Can JavaScript Do?</h2>
<p id="demo" onclick="myFunction()">Click me.</p>