Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the width of an element using AngularJS?

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?

like image 685
Lupus Avatar asked Feb 04 '14 04:02

Lupus


People also ask

How do you find the width of an element?

The offsetWidth property returns the viewable width of an element (in pixels) including padding, border and scrollbar, but not the margin. The offsetWidth property is read-only.

Which method returns the width of an element?

The outerWidth() method returns the width of an element (includes padding and border).

How do you find the width of an element in pixels?

To get the width of a specific HTML Element in pixels, using JavaScript, get reference to this HTML element, and read the clientWidth property of this HTML Element. clientWidth property returns the width of the HTML Element, in pixels, computed by adding CSS width and CSS padding (top, bottom) of this HTML Element.


Video Answer


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.

like image 170
Kasper Lewau Avatar answered Oct 09 '22 03:10

Kasper Lewau


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); 
like image 28
Post Impatica Avatar answered Oct 09 '22 04:10

Post Impatica