Get DIV width and height in javascript - 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?

It's quite wrong to use ele.style.width to get the element's width!!!!!!
In native JavaScript, you can get a element's CSS through two ways:
Standard Method
window.getComputedStyle(ele)
For example,
var ele = document.getElementById("content"), // Do not use #
eleStyle = window.getComputedStyle(ele);
/* Below is the width of ele */
var eleWidth = eleStyle.width;
IE(IE 8 And Before)
element.currentStyle
For example,
var ele = document.getElementById("content"), // Do not use #
eleStyle = ele.currentStyle;
/* Below is the width of ele */
var eleWidth = eleStyle.width;
Why Not Use ele.style?
ele.style is just get the attribule style of ele. If you use ele.style.width, you just get the width of ele.style, not the real width of ele.
If you have done something like:
ele.style.width = "55px"
You get "55px" when using ele.style.width. If you haven't, you will get undefined.
How To Do In jQuery?
Use $ele.width() (if you want the "exact" width, use $ele.outWidth()), jQuery has done everything for you.

In plain vanilla JavaScript use
var width = mydiv.offsetWidth;
var height = mydiv.offsetHeight;
This will give you numeric values, or
var width = mydiv.offsetWidth + 'px';
var height = mydiv.offsetHeight + 'px';
If you want them in "CSS" format.

Since you're already using jQuery, you can just do:
var width;
if (need == 1) {
width = $("#web").width();
} else {
width = $("#set").width();
}

Since you're using jQuery, you'll probably want to know about the following:
$('#id').outerWidth()
$('#id').outerWidth(true)
These will come in very handy. This allows you to find the total width of the div (padding, border, width and (optional argument) margin).
http://api.jquery.com/outerWidth/

Related

Add width and height attr to all images

I need width and height attributes added to all images on a page via javascript/jquery. This is due to a tool our systems use. I thought a simple each loop, adding height/width attr would suffice. Unfortunately this doesn't seem to work
DEMO https://jsfiddle.net/z86xnqd7/
$('body').find('img').each(function (index) {
var theWidth = index.width();
var theHeight = index.height();
index.attr({
"width": theWidth,
"height": theHeight
});
});
When you inspect element you will notice no width/height attr has been added
jsFiddle : https://jsfiddle.net/CanvasCode/z86xnqd7/6/
You need to do your each on the load event, you need to make sure your image has loaded before you check its height and width. Also you want to use $(this) instead of index.
$(function () {
$('img').load(function () {
var theWidth = $(this).width();
var theHeight = $(this).height();
$(this).attr({
"width": theWidth,
"height": theHeight
});
});
});
It's because index is real iteration index (e.g. 1, 2...). Use $(this) or add second parameter to function header function (index, element) {}:
$.each($('img'), function () {
$(this).attr({
width: $(this).width(),
height: $(this).height()
});
});
Problem here is that you try to get the width and height from the index which is just a number and no jQuery object. Try this - it will do the job:
$('body').find('img').each(function(i, elem) {
var $this = $(this);
var theWidth = $this.width();
var theHeight = $this.height();
$this.attr({"width": theWidth, "height": theHeight});
});
See js fiddle: https://jsfiddle.net/g4nn2pk0/2/

How to change style in javascript

What is wrong with my code? I am trying to change the sizes of two boxes when the button is clicked:
<script type="text/javaScript>
document.getElementById("makesmaller").onclick=function(){
document.getElementById("bigbox").style.size="100px".color="green";
}
document.getElementById("makebig").onclick=function(){
document.getElementById("littlebox").style.size="1000px".color="red";
}
</script>
Firstly, there is no "size" style
There's width, height, fontSize, and I'm sure there's others, but not size
Here's what might do what you want.
document.getElementById("makesmaller").onclick=function(){
var el = document.getElementById("bigbox");
el.style.height="100px";
el.style.width="100px";
el.style.color="green";
}
Similarly for the makebig part
There is no documentation of a size property in CSS. What you are most likely looking for is the CSS width and height properties.
Javascript syntax for such an operation would reside in the following code:
var element = [HTML Element]; // Get HTML Element
var width, height; // Set width and height variables
element.style.width = width;
element.style.height = height;
To do so upon the calling of an onclick event, the resulting code would be written along the following lines:
// Listen for click event
element.addEventListener("click",
function() {
element.style.width = width; // Set new width
element.style.height = height; // Set new height
});
To do exactly what you are aiming for, your code would be based on this logic:
// Get buttons
var bigger = [HTML Element],
smaller = [HTML Element];
// Set size variables
var bigger_width, bigger_height;
var smaller_width, smaller_height;
// Add handlers
bigger.addEventListener("click",
function() {
element.style.width = bigger_width;
element.style.height = bigger_height;
});
smaller.addEventListener("click",
function() [
element.style.width = smaller_width;
element.style.height = smaller_height;
});
Alternatively, one could use the element.onclick = function() { } syntax.
Use width, height and cssText. There is no property in CSS called "size". By using cssText you can change multiple properties without using jQuery( e.g element.css({"height": "100px", "width": "100px"})
JSFiddle: https://jsfiddle.net/2as3get3/2/
<script type="text/javaScript>
document.getElementById("makesmaller").onclick = function(){
document.getElementById("littlebox").style.cssText = "width: 100px; height: 100px; color: green;";
}
document.getElementById("makebig").onclick = function(){
document.getElementById("littlebox").style.cssText = "width: 1000px; height: 1000px; color:red; ";
};
</script>

Show current div size in html text

I try to show current the width and height of a div in another div. I use the resize: both on the div I am trying to measure. The problem I have now is that the numbers do not update when I resize the div.
$(function () {
var divheight = $("#resizediv").height();
var divwidth = $("#resizediv").width();
document.getElementById("divheightdisplay").innerHTML = divheight;
document.getElementById("divwidthdisplay").innerHTML = divwidth;
});
Fiddle
I also tried CSS Element Queries. But have some problems with overflow: hidden
The resize event does not seem to apply to elements other than the window.
Instead, you could update based on the mousemove event:
$('#resizediv').on('mousemove', function() {
var divheight = $(this).height(),
divwidth = $(this).width();
$('#divheightdisplay').html(divheight);
$('#divwidthdisplay').html(divwidth);
});
Fiddle
If the content of your divs are loaded dynamically, then you will need to use window.load event to get the correct size:
$(window).load(function() {
var divheight = $("#resizediv").height();
var divwidth = $("#resizediv").width();
document.getElementById("divheightdisplay").innerHTML = divheight;
document.getElementById("divwidthdisplay").innerHTML = divwidth;
});
You will have to call a callback function, which updates the values of width and height, on resizing your div.
//Say this is the function which is resizing your div
resize("#resizediv", callback());
function callback() {
var divheight = $("#resizediv").height();
var divwidth = $("#resizediv").width();
document.getElementById("divheightdisplay").innerHTML = divheight;
document.getElementById("divwidthdisplay").innerHTML = divwidth;
}

Add pixels to existing CSS element with Javascript

here is my trouble.
I'm using a plugin for a lightbox. For some reason, one of the divs is 28px too short. I've looked all over for a solution for this, but nobody seems to be having the same problem.
The solution I've come up with is to find that element (which I have) and create a javascript snippet that will add "28" to the existing number. The height and width is being calculated directly on the div, not in an element in a stylesheet.
Example:
<div id="colorbox" class="" style="padding-bottom: 57px; padding-right: 28px; position: absolute; width: 892px; height: 602px; top: 2234px; left: 500px;">
I want the Javascript code to add 28 pixels to the width and 55px to the height.
How would I go about doing this?
I would like to say that I'm not looking for just an answer; if you could explain it to me, that would be great. Thanks so much, guys!
Edit: this is how I called the JQuery
Also, this is where you can see the page with the gallery: http://olsencustomhomes.com.previewdns.com/designs/verona-2/#gallery
EDIT FOR KRIS:
Is this the right code? It's in my header
<script>
$(document).ready(function() {
function changeSize(){
var colorbox = $("#colorbox");
var initWidth = $("#colorbox").outerWidth(); // get colorbox width
var initHeight = $("#colorbox").outerHeight(); // get colorbox height
var newWidth = 28; // set your desired width
var newHeight = 55; // set your desired height
var height = initHeight + newHeight; // add heights together
var width = initWidth + newWidth; // add widths together
colorbox.css({"height" : height, "width": width});
}
$(document).ajaxStop(function() {
changeSize();
});
});
</script>
Pretty straightforward application of jQuery, but I commented it up for you anyway:
//select the box element using jQuery
var box = $('#colorbox');
//get the current width and height
var curWidth = box.width();
var curHeight = box.height();
//set the width and height with modified values
box.width(curWidth + 28);
box.height(curHeight + 55);
fiddle: http://jsfiddle.net/579s2/
If you want to add height and width dynamically. Something like this should work:
function changeSize(){
var colorbox = $("#colorbox");
var initWidth = $("#colorbox").outerWidth(); // get colorbox width
var initHeight = $("#colorbox").outerHeight(); // get colorbox height
var newWidth = 28; // set your desired width
var newHeight = 55; // set your desired height
var height = initHeight + newHeight; // add heights together
var width = initWidth + newWidth; // add widths together
colorbox.css({"height" : height, "width": width});
}changeSize();
Also if you want to insure your code is happens after the colorbox opens you could use .ajaxStop(); Also note, outerWidht() and outerHeight() will get colorbox width plus the padding and borders.
To fire function after ajax events are finished:
$(document).ajaxStop(function() {
changeSize();
});
Update:
Okay, it looks the function fires initially. You can see width is null because the colorbox has not opened. What you want to do is fire the function after the colorbox opens. That is where ajaxStop() would come into play. But it might actually be better to use the colorbox callback function:
But not after the colorbox opens. So try doing the ajaxStop() approach. Also note, if you do this you will need to remove changeSize(); after function changeSize() For example:
$(document).ready(function() {
function changeSize(){
// function stuff
}
$(document).ajaxStop(function() {
changeSize();
});
});
Or, Colorbox OnComplete:
$(".selector").colorbox({
onComplete:function(){
changeSize();
}
});
Update 2:
I am not sure where you are calling colorbox exactly. But I see you have this: Found here
jQuery(function($){
$('#wpsimplegallery a').colorbox({
maxWidth: '85%',
maxHeight: '85%'
});
});
So try:
jQuery(function($){
$('#wpsimplegallery a').colorbox({
maxWidth: '85%',
maxHeight: '85%',
onComplete:function(){
changeSize();
}
});
});

How to make a drop down menu the same width as the trigger button

In an image this is what I'm trying to accomplish:
This is how i'm starting out the js:
$(document).ready(function(){
var userWidth = $('#userOptions.width()');
var menuWidth = $('#userOptionsMenu.width()')
function menuMatch() {
if(menuWidth < userWidth) {
menuWidth = userWidth;
}
}
menuMatch();
});
Here is an image with the ID's:
In function menuMatch() i'm not sure how to write in JS how to make something equal in width to the element it's currently narrower than.
Does that make sense?
Thanks.
Here's a link to a codepen http://codepen.io/MARS/pen/cGwbC
You're pulling the jQuery width property incorrectly. Change this:
var userWidth = $('#userOptions.width()');
var menuWidth = $('#userOptionsMenu.width()')
to this:
var userWidth = $('#userOptions').width();
var menuWidth = $('#userOptionsMenu').width();
This will get you the width you need to set. Then to correctly apply the css, you need to do this:
function menuMatch() {
if(menuWidth < userWidth) {
$("#userOptionsMenu").css("width", userWidth + "px");
}
}
You have two issues:
1) You included width() within the selector. The function should be called after the selector.
2) You need to set the width using width() as a selector, instead of just modifying the variable you set $('#userOptionsMenu').width() equal to.
$(document).ready(function(){
var userWidth = $('#userOptions').width(); // These should be
var menuWidth = $('#userOptionsMenu').width(); // outside of the quotes
function menuMatch() {
if(menuWidth < userWidth) {
$('#userOptionsMenu').width(userWidth); // Change the value of
} // the width using
} // width() as a setter.
menuMatch();
});

Categories

Resources