Tell me how to track the size of an element in real time without jquery?

For example, there is div1 and there is div2 and I want to transfer some of the width of the first one to the second one in real time, roughly speaking I change the first one - the second one also changes.

  • Not sure, but google "getcomputedstyle". - alvoro

1 answer 1

The width of the element can be obtained using window.getComputedStyle . For IE8, you can use element.clientWidth or .offsetWidth . The first property also includes padding , the second - padding , border and scrollbar width.

Further, in order to track changes, in new browsers you can use Mutation observer . In IE up to the 11th version - onpropertychange. Change Tracking Code:

 function listenerCreate(src, dst){ function changeWidth(){ var newWidth=getDivWidth(src); if(src.oldWidth!=newWidth){ dst.style.width=src.oldWidth=newWidth; } } src.oldWidth=getDivWidth(src); if(typeof(MutationObserver) !== 'undefined'){ var MO=new MutationObserver(changeWidth); MO.observe(src, { attributes: true, childList: true, characterData: true }); } else { src.onpropertychange = changeWidth; } } 

The complete example is on JSFiddle . By the way, a curious bug: you can get a CSS property using getComputedStyle from a function on this site just by adding an empty string to it. It probably has something to do with frames.

  • Now I will understand, honestly admit surprised by such cumbersome code, how much easier it is to work with jquery. - kils
  • @kils and you really thought that jQuery wrote nothing better to do? - zb '