Search code examples
javascriptjqueryajaxhtmlsize

Get DIV width and height in javascript


I'm trying to get the div width and height as the user changes it and submit that number to another page. I can't seem to figure out how to get the width and height though.

<script>
$(function() {
  $( "#set div" ).draggable({ 
    stack: "#set div",
    preventCollision: true,
    containment: $('#main_content'),
      stop: function(event, ui) {
          var mydiv = document.getElementById("set");
          var pos_x = ui.offset.left;
          var pos_y = ui.offset.top;

          var width = mydiv.style.width;        ----THIS DOESN'T WORK
          var height = mydiv.style.height;      ----THIS DOESN'T WORK

          var window_width = window.innerWidth;
          var window_height = window.innerHeight;
          var need = ui.helper.data("need");

          console.log(pos_x);
          console.log(pos_y);
          console.log(width);
          console.log(window_width);
          console.log(need);

          //Do the ajax call to the server
          $.ajax({
              type: "POST",
              url: "updatecoords.php",
              data: { x: pos_x, y: pos_y, need_id: need, width: width, height: height, window_width: window_width, window_height: window_height}
            }).done(function( msg ) {
              alert( "Data Saved: " + msg );
            });  
      }
  });
});
</script>

What's the proper way to do this?


Solution

  • Since you're already using jQuery, you can just do:

    var width;
    
    if (need == 1) {
       width = $("#web").width();
    } else {
       width = $("#set").width();
    }