How to do div with scroll, when it reaches a certain limit of div height?

Asked

Viewed 93 times

1

How can I get my div, whose text is added through a append jQuery, scroll when the text reaches 100px, and all the added text then stay hidden, and you need to scroll to see the rest?

inserir a descrição da imagem aqui

$('#sendMessage').click(function() {
  if ($.trim($('#inputToSend').val()) == '') {
    //do not send anything
  } else {
    $('.textModal').append('<p class="msg" style="margin-bottom: 25px; position: absolute;">' + $('#inputToSend').val() + '</p>' + '<br>');
    $('#inputToSend').val('').focus();
  }
});
.textModal {
  margin: 0px 15px;
  font-size: 16px;
  padding: 10px;
  border: inset;
  height: 100px;
  overflow: auto;
  text-align: justify;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="messageInput">
  <div class="textModal"></div>
  <input id="inputToSend" type="text" class="text form-control" placeholder="Insert Message...">
  <button id="sendMessage" class="btn btn-primary">Enviar</button>
</div>

1 answer

3


The problem is you’re putting position: absolute paragraphs. This causes them to be "loose" on the page and will not obey the overflow rule. Nor does it need the <br> between paragraphs. Only use <br> to break line between inline elements, and paragraphs are block elements. It is also unnecessary to margin-bottom: 25px. The paragraphs already have a margin top and bottom standard, which you can adjust as you like through the class .msg.

Then it would be enough to make the append this way:

$('.textModal').append('<p class="msg">' + $('#inputToSend').val() + '</p>');

Regarding the paragraph margins, you could take the upper margin and reduce the lower to 10px, for example:

.msg{
   margin: 0 0 10px 0;
}

Take an example:

$('#sendMessage').click(function () {
   if($.trim($('#inputToSend').val()) == ''){
      //do not send anything
   } else {
      $('.textModal').append('<p class="msg">' + $('#inputToSend').val() + '</p>');
      $('#inputToSend').val('').focus();
   }
});
.textModal {
    margin: 0px 15px;
    font-size: 16px;
    padding: 10px;
    border: inset;
    height: 100px;
    overflow: auto;
    text-align:justify; 
}

.msg{
   margin: 0 0 10px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="messageInput">
   <div class="textModal"></div>
   <input id="inputToSend" type="text" class="text form-control" placeholder="Insert Message...">
   <button id="sendMessage" class="btn btn-primary">Enviar</button>
</div>

Browser other questions tagged

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