How to get the position of the hidden item through display:none ?

Example:

 console.log('Left: '+ $(".row").offset().left); 
 .row { display: none; margin: 20px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="row">Text</div> 

  • one
    Show an element, take its position, hide an element - Regent
  • @Regent, good decision, take note - Bert

1 answer 1

The fact is that when you apply display:none to an element, the browser stops worrying about rendering it, so you cannot access the parameters you are interested in (which is possible with visibility: hidden ), but there is one trick here if you apply visibility: hidden , then show the element through display: block (that is, the element is also invisible, but the browser rendered it), get the data you need and return everything back.

An example of getting the parameters of a hidden item through display: none :

 //копируем текущие стили в переменную var previousCss = $(".row").attr("style"); //скрываем элемент через visibility:hidden. даем браузеру сделать рендер //через dipslay:block $(".row") .css({ visibility: 'hidden', display: 'block' }); //Получаем нужные параметры let height = $(".row").height(); let width = $(".row").width(); let leftOffset = $(".row").offset().left; let topOffset = $(".row").offset().top; console.log('heigth: ' + height); console.log('width: ' + width); console.log('leftOffset: ' + leftOffset); console.log('topOffset: ' + topOffset); //Применяем начальные стили обратно $(".row").attr("style", previousCss ? previousCss : ""); 
 div.row { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="row">Text</div>