How do I know if the text has passed a div? using JS

-1

#btn{
  
  width: 100px;
  height: 100px;
  background-color: red;
  cursor: pointer;
  overflow: hidden;
}
<div id="btn">
  Lorem ipsum dolor sit amet consectetur, adipisicing elit. Dignissimos nostrum nam ex optio sequi quam atque repellat debitis eveniet excepturi ad corporis velit nesciunt qui, necessitatibus sapiente magni in autem.
  
</div>
    
asked by anonymous 25.03.2018 / 16:31

2 answers

1

There's no way to know text dimensions if it's not surrounded by a tag ( I've already asked a relative question here ).

What you can do is wrap the text in a span tag and set display: inline-block to span so that it has dimensions, that is, it will have the same dimensions as the text it occupies. This does not affect the flow of code at all.

Then you capture the height of span with clientHeight .

See an example:

var div = document.querySelector("#btn").clientHeight;
var texto = document.querySelector("#btn span").clientHeight;

var checa = div-texto; // diminuo a altura da div pelo span do texto

console.log("A div tem "+div+"px de altura");
console.log("O texto tem "+texto+"px de altura");

// se "checa" for negativo, significa que o texto ultrapassou a div
if(checa < 0){
    console.log("O texto é maior que a div");
}else{
    console.log("O texto é menor que a div");
}
#btn{
  
  width: 100px;
  height: 100px;
  background-color: red;
  cursor: pointer;
  overflow: hidden;
}

#btn span{
   display: inline-block;
}
<div id="btn">
  <span>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Dignissimos nostrum nam ex optio sequi quam atque repellat debitis eveniet excepturi ad corporis velit nesciunt qui, necessitatibus sapiente magni in autem.</span>
</div>
    
25.03.2018 / 22:56
0

I think that visually even though it is work, but with jQuery it can be resolved like this:

<script>
if ($('#div-id')[0].scrollWidth >  $('#div-id').innerWidth()) {
    window.alert('Texto excedeu as dimensões da div');
}
</script>

You can put the action in .onload , .onclick , .onReady . It's up to you.

    
25.03.2018 / 18:31