I realise I can use jQuery to get the width of an element, but I'm curious; is there a way to do so using AngularJS?
2 Answers
Native JS (#id):
document.getElementById(id).clientWidth;
Native JS (querySelector (class, id, css3 selector)):
document.querySelectorAll(".class")[0].clientWidth;
Plugging this into angular.element:
angular.element(document.getElementById(id)).clientWidth;
angular.element(document.querySelectorAll(".class")[0]).clientWidth;
If you need to get non rounded numbers, use getBoundingClientRect.
angular.element(document.getElementById(id)).getBoundingClientRect();
Some resources on the subject:
- http://msdn.microsoft.com/en-us/library/hh781509(VS.85).aspx
- https://developer.mozilla.org/en-US/docs/Web/API/Element.clientWidth
- https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect
If this floats your boat in terms of syntax and the no-need to plug jQuery into the mix, be wary of cross browser hell.
2 Comments
Zach Lysobey
Maybe I'm missing something, but the
angular.element examples don't work for me. I think you need to unwrap the DOM element from its jqLite wrapper in order to access basic DOM methods/properties. i.e. angular.element(document.getElementById(id))[0].clientWidth;, NOT angular.element(document.getElementById(id)).clientWidth; This of course makes the whole angular.element thing in this example silly, but it is necessary to do something like this to get at the vanilla dom element from, say, a link functions element.azuax
@ZachLysobey is right...at least in Chrome, you need to select the first element: angular.element(document.getElementById(id))[0].clientWidth
If you've been scratching your head like me over all these suggestions and they don't work, i found i had to set a timeout. I'm not sure why, maybe because i'm using material design attributes on my divs.
setTimeout(function(){
var divsize = angular.element(document.getElementById('fun_div')).prop('offsetWidth');
console.log('Width of fun_div: ' + divsize);
},50);
2 Comments
HammerNL
Using setTimeout for this purpose is not a good idea. In this case you assume the browser will have finished rendering everything you need within 50ms. I'm sure a modern PC can handle that, but what about a budget smartphone? Use Angulars $timeout instead, it guarantees all rendering has finished, before calling your function.
Post Impatica
@HammerNL I agree.
$('element').width();in js.. replaceelementwith use of your ID or class. Reference : api.jquery.com/widthgetBoundingClientRect. It will give you a width as well as other useful numbers.