How to know if the text surpassed a div? using JS

Asked

Viewed 168 times

-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>

  • overtaken in the x-axis, the y-axis, or both?

2 answers

1


There is no way to know text dimensions if it is not surrounded by a tag (I have already asked a question about this).

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

Then you capture the height of the span with clientHeight.

Take 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>

0

I believe that visually even being work, but with jQuery can be solved 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 on .onload, .onclick, .onReady. Goes from your need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.