What if, if the value is false, the actions are still performed?

  • 0
    I have this javascript code
    if(document.getElementById("background_bar").style.height == 80 + "px" || document.getElementById("background_bar").style.height > 80 + "px" ){
                var star1 = $('#star1');
            console.log(star1.attr('class'));
            star1.removeAttr('class', 'star1-und');
            star1.attr('class', 'star1-yes');
            var star2 = $('#star2');
            console.log(star2.attr('class'));
            star2.removeAttr('class', 'none');
            star2.attr('class', 'star2-und');
    
            var star1l = $('#stars');
            console.log(star1l.attr('class'));
            star1l.removeAttr('class', 'none');
            star1l.attr('class', 'star1line');
    
            document.getElementById('stars').src = '/img/Stars_1.png'
    
            star1s()
            stars = 1;
            }


    If the element's height is 80 pixels or more than 80 pixels, then actions are taken. Well, if the height of the element is much less than 80 pixels (for example, the height is 4 pixels), then the action is performed for some reason. What to do?

    P.S. until I added
    || document.getElementById("background_bar").style.height > 80 + "px"
    when the element was 80 px high then everything was correct.
    JavaScript Anonymous, Jun 24, 2020

  • 1 Answers
  • 0
    You are using typecasting incorrectly in JavaScript. In fact, your code is not comparing the block height with a given number, but a string with another string, which is why the behavior is so strange. It is correct to write like this:

    (function (){
    "use strict";

    var bgBlock = document.getElementById("background_bar");

    if (bgBlock.scrollHeight > 80) { // bgBlock.scrollHeight всегда число
    // Какой-то код, который выполняется для высоты меньше 80 px
    } else {
    // Другой код, если блок меньше
    }
    }());




    More here .
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!