Monday, 28 March 2016

How to work with dimensions of elements and browser window ?


width() and height()

Sets / returns the width or height of an element (includes NO padding, border or margin)
Example   Returns the width and height of a specified div element
$("button").click(function() {
  var txt="";
  txt += "Width: " + $("#div1").width() + "</br>";
  txt += "Height: " + $("#div1").height();
  $("#div1").html(txt);
});


innerWidth() and innerHeight()

Returns the width or height of an element (includes padding)
Example Returns the inner-width/height of a specified div element
$("button").click(function() {
  var txt="";
  txt+="Inner width: " + $("#div1").innerWidth() + "</br>";
  txt+="Inner height: " + $("#div1").innerHeight();
  $("#div1").html(txt);
});


outerWidth() and outerHeight()

Returns the width or height of an element (includes padding and border)
Example  Returns the outer-width/height of a specified div element
$("button").click(function() {
  var txt="";
  txt+="Outer width : " + $("#div1").outerWidth() + "</br>";
  txt+="Outer height : " " + $("#div1").outerHeight();
  $("#div1").html(txt);
});

outerWidth(true) and outerHeight(true)
Returns the width or height of an element (includes padding, border, and margin)
Example
$("button").click(function() {
  var txt="";
  txt+="Outer width (+margin): " + $("#div1").outerWidth(true) + "</br>";
  txt+="Outer height (+margin): " + $("#div1").outerHeight(true);
  $("#div1").html(txt);
});


More examples of width() and height()
Example 1
Returns the width and height of the document (the HTML document) and window (the browser viewport)
$("button").click(function() {
  var txt="";
  txt+="Document width/height: " + $(document).width();
  txt+="x" + $(document).height() + "\n";
  txt+="Window width/height: " + $(window).width();
  txt+="x" + $(window).height();
  alert(txt);
});

Example 2  Sets the width and height of a specified div element
$("button").click(function() {
  $("#div1").width(500).height(500);
});



No comments:

Post a Comment

Note: only a member of this blog may post a comment.