Home > Mobile >  Javascript 100% width of an Element
Javascript 100% width of an Element

Time:12-18

Hi is there any way to check if an element like a progress bar has 100% width?

I've tried this but it does not work

let i = 0;
function start() {
    if (i == 0){
        i = 1;
        let elem = document.getElementById("myBar");
        let width = 10;
        let id =  setInterval(frame, 60);

        function frame() {
            if (elem.getAttribute("width") >= '100 %') {
                document.getElementsByTagName('form')[0].submit();
                clearInterval(id);
                i = 0;
            }
            else {
                width  ;
                elem.style.width = width   '%';
            }
        }
    }
}

Edit: html Code:

<div id ="myProgress">
   <div id="myBar"></div>
</div>

CodePudding user response:

If you need raw property from style use element.style.width it will return string value (if setted through style attribute). If you need result value use window.getComputedStyle(element).width this will returns value in px

relates to: How to get an HTML element's style values in JavaScript?

CodePudding user response:

Empty divs won't take space by default, you either need to add content inside it, or use CSS

Additionally if (elem.getAttribute("width") >= '100 %') should be if (width >= 100)

function start() {
  let elem = document.getElementById("myBar");
  let width = 10;
  let id = setInterval(frame, 60);

  function frame() {
    if (width >= 100) {
      // document.getElementsByTagName('form')[0].submit();
      clearInterval(id);
      width = 10;
    } else {
      width  ;
      elem.style.width = width   '%';
    }
  }
}

start()
#myProgress {
  background-color: #ccc;
  width: 100%;
}

#myBar {
  background-color: #00ff00;
  width: 0%
}

#myBar:after {
  content: '\200b';
}
<div id="myProgress">
  <div id="myBar"></div>
</div>

  • Related