1

There is a div with class set to col-md-7 and width attribute is not set.

I've to get the width of this div whenever the window is resized.

When I set width explicitly, I can access it in the resize event but when I don't set width and use col-md-7, using element.getAttribute("width") returns null.

How can I solve this problem?

CODE

var canvas = document.getElementById('myCanvas');    
var canvasHolder = document.getElementById("receiptHolder2");    
initialize();
function initialize() {

    window.addEventListener('resize', resizeCanvas, false);


    resizeCanvas();
  }
  function redraw(){
    var backgroundImage = new Image();
    backgroundImage.onload = function(){
      canvas.setAttribute("height",500);
      canvas.setAttribute("width",300);
      var context = canvas.getContext('2d');
      alert(canvasHolder.width); // this line gives null
      context.drawImage(backgroundImage,0,0,300,500);
    }        
    backgroundImage.src="https://www.bhphotovideo.com/images/images500x500/Savage_1_12_107_x_12yds_Background_45468.jpg";        
  }

  function resizeCanvas() {
    canvas.width = canvasHolder.innerWidth + 30;
    canvas.height = canvasHolder.innerHeight + 30;
    redraw();
  }
Zain Ul Abideen
  • 41
  • 1
  • 1
  • 5

4 Answers4

0

If your element col-md-7 so you can do like this:

var width = document.getElementsByClassName("col-md-7");.clientWidth;

So in width variable you will get the width.

Himanshu Upadhyay
  • 6,558
  • 1
  • 20
  • 33
0

This element.getAttribute("width") dont seems to be a valid as width is not an attribute but it is a style property.

Hopefully you will be able to use document.querySelector & getComputedStyle

// will get the first div with this class
var getElem = document.querySelector('.col-md-7');
//use getComputed style to get width 
var theCSSprop = window.getComputedStyle(getElem ,null).getPropertyValue("width"); 
brk
  • 48,835
  • 10
  • 56
  • 78
0

if your element id is col-md-7. you can get with of the element like this

document.getElementById("col-md-7").offsetWidth

For more detail see this HTMLElement.offsetWidth

Gaurang Ghinaiya
  • 559
  • 9
  • 26
-1

You can set the width of element,

$("#clc-tlb").width("800px");

and you can get it by,

$("#clc-tlb").width();
Dui Samarasinghe
  • 247
  • 2
  • 10