A
A
Alexey Konovalov2020-05-13 13:35:41
JavaScript
Alexey Konovalov, 2020-05-13 13:35:41

How to load data via aJax and insert into page without bouncing?

Hello! I'm trying to make a smooth insertion of data received via Ajax into the page. The idea is that the block already has some content, by clicking on the button, other content is loaded and inserted into the already existing block.
because in the response comes ready html containing images it turns out that after inserting the received content, the existing block is first reduced to a height of 0 (because the images have not loaded yet), and then increases as the images are loaded. Very unpleasant jumps turn out.
I tried to fix the size of the existing block before inserting, using height and overflow, and then calculate the height of all elements that came from Ajax and use $.animate() to increase the height to the received one, but I didn’t succeed, because I can not determine the moment at which the images are already loaded on the page and at what moment it is "already time" to calculate the height of the elements?
Plz tell me what I'm doing wrong. Here's what I got:

$('.show_full').on('click', '.btn', function(){
  let th = $(this);
  $.ajax({
    url: '/testAjax.php',
    method: 'GET',
    dataType: 'JSON',
    beforeSend: function(){
      th.html('<div class="spinner"></div>');
    }
  }).done(function(content){
    if(content){

      let innerBlock = th.closest('.post_main');
      

      let oldH = innerBlock.outerHeight();
      innerBlock.css('height', oldH).css('overflow', 'hidden');

      // надеялся на InnerHTML, т.к. он загружает данные, но он не помог
      let div = document.createElement('div');
      div.innerHTML = content;
      // не дожидаясь загрузки, данные вставляются в блок и контент прыгает
      innerBlock.html(div.innerHTML);

      innerBlock.css('height', "");

      return;
    }
  }).fail(function(){
    alert("Err");
  });
})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shsv382, 2020-05-13
@shsv382

Set the height of the block in advance, and nothing will bounce

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question