Home > Software engineering >  Loop the script for get the correspondent of the element
Loop the script for get the correspondent of the element

Time:11-01

I want to reduce the text font-size till text has some height (in the example 54px). But the script does this only 1 time (read height only by load and not anymore). I can not loop this.

https://jsfiddle.net/Nata_Hamster/zpvhow68/

$(document).ready(function() {
  let fact1 = $('div');
  let fact1_h = fact1.height();
  let fact_fs = parseInt($('div').css('font-size'));
  alert(fact_fs);

  if (fact1_h > 54) {
    fact_fs -= 1;
    fact1.css({
      'font-size': fact_fs   'px'
    });
    alert(fact_fs);
    fact_fs = parseInt($('div').css('font-size'));
  }
});
div {
  width: 200px;
  padding-left: 20px;
  padding-right: 20px;
  font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div>JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. </div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You do need to loop but you also need to give the interface time to adjust

$(function() {
  const fact1 = $('div');
  const tID = setInterval(function() {
    let fact1_h = fact1.height();
    let fact_fs = parseInt($('div').css('font-size'));
    if (fact1_h <= 54) {
      clearInterval(tID)
      return
    }
    fact_fs -= 1;
    fact1.css({
      'font-size': fact_fs   'px'
    });
  }, 10);
})
div {
  width: 200px;
  padding-left: 20px;
  padding-right: 20px;
  font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div>JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. </div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You may use while statement that will execute the given statement as long as the given condition is true.

$(document).ready(function() {
  let fact1 = $('div');
  let fact1_h = fact1.height();
  let fact_fs = parseInt($('div').css('font-size'));
  console.log('Initial font size', fact_fs);

  while (fact1_h > 54) {
    fact_fs -= 1;
    fact1.css({
      'font-size': fact_fs   'px'
    });
    fact1_h = fact1.height();
    console.log('New Font - ', fact_fs);
    console.log('New Height - ', fact1_h);
  }
});
div {
  width: 200px;
  padding-left: 20px;
  padding-right: 20px;
  font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div>JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. </div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related