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>
Related
I was wondering how I could constantly get the current browser's height and width. Right now, I am using jQuery and have something like this:
var height = window.innerHeight;
var width = window.innerWidth;
This does initially work as it gets the screen when the page is loaded up. However, when the user changes the screen width/height manually, I can't seem to get the current dimensions and the page starts faulting with errors. How should I be checking the dimensions at all times? I've tried googling the answer but I can't seem to find anything applicable, though I'm sure many others have had the same issue (I don't think I'm searching up the right keywords!). Please let me know what I can do!! Thanks!
Use a window.onresize function as well as a window.onload handler to update the width and height variables.
(Resizeable Demo)
var width,height;
window.onresize = window.onload = function() {
width = this.innerWidth;
height = this.innerHeight;
document.body.innerHTML = width + 'x' + height; // For demo purposes
}
Using jQuery objects it would look like this.
(Resizeable Demo)
var width,height;
$(window).on('load resize', function() {
width = this.innerWidth; // `this` points to the DOM object, not the jQuery object
height = this.innerHeight;
document.body.innerHTML = width + 'x' + height; // For demo purposes
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this:
$(window).on("resize",function(){
console.log($(this).height() + " " + $(this).width());
});
fiddle
Try this
var width = window.outerWidth;
var height = window.outerHeight;
To resize the current window, use
window.resizeTo(width, height);
You can trigger the resize function using:
$( window ).resize(function() {
//....
});
Hope it helps you
You can use this to detect a change in screen size:
$(window).resize(function() {
height = window.innerHeight;
width = window.innerWidth;
//other code you wish to run on screen size change;
});
This assumes that height and width were declared in a scope that the function has access to. Otherwise make sure to place var before each variable.
I want two elements in different locations and different "parents" in the DOM tree to have the same height and width, even if one changes.
Is there a solution that will support all browsers including IE 8?
EDIT: If there is a solution that will not work on IE 8 I would still like to hear about it, but it will not be accepted as the solution I'm looking for.
Clarification: I want to solution to handle any cause for the size change: Window size change, content size change, etc.
You can use setInterval to do what you want.
var changeIndex = -1; // record element width or height is change or not
function setToSame() {
if(changeIndex!=-1) {
console.log("test");
$('.same').height($('.same').eq(changeIndex).height());
$('.same').width($('.same').eq(changeIndex).width());
changeIndex = -1;
}
}
// set your own function to change size, but reserve changeIndex setting
$('input').change(function() {
$(this).parent().children('.same').css($(this).attr('id'), $(this).val() +'px');
// set the changeIndex to the current change div
changeIndex = $('.same').index($(this).parent().children('.same'));
console.log(changeIndex);
});
setInterval(setToSame, 4);
See jsfiddle here.
You can use jQuery to get a solution that works for IE8.
Suppose the two element that you want to have same height and width are,
<div id="fir">
</div>
<div id="sec">
</div>
Now specify height and width of just one element as,
#fir{
height: 50px;
width: 100px;
}
There is no predefined method in CSS to detect height or width change but you can achieve the results using jQuery as,
$(document).ready(function(){
$('#fir').bind('heightChange', function(){
var h = $("#fir").height();
$("#sec").height(h);
});
$('#fir').bind('widthChange', function(){
var w = $("#fir").width();
$("#sec").width(w);
});
$('#sec').bind('heightChange', function(){
var h = $("#sec").height();
$("#fir").height(h);
});
$('#sec').bind('widthChange', function(){
var w = $("#sec").width();
$("#fir").width(w);
});
});
This will detect the height and width change for both element and set the height and width of other element likewise.
To check if the above code works properly you can create a test script that changes width of element with id="fir" by creating a button,
<button id="btn">Change width</button>
Now include the below function,
$("#btn").click(function() {
$("#fir").css('width', '400px');
$("#fir").trigger('widthChange');
});
Here is the fiddle for it
<html>
<head>
<style>
div{}
#A{background: red}
#B{background: blue}
</style>
<script>
mBlockChange = false; //Required for IE9-
function equalSize(f, t){
mBlockChange = true;
f = (f || document.getElementById('A'));
t = (t || document.getElementById('B'));
//We take the larger dimension of both since it is better than clipping.
//Change on your demands.
t.style.height = '';
t.style.width = '';
f.style.height = '';
f.style.width = '';
t.style.height = Math.max(f.offsetHeight, t.offsetHeight).toString() + 'px';
t.style.width = Math.max(f.offsetWidth, t.offsetWidth).toString() + 'px';
f.style.height = Math.max(f.offsetHeight, t.offsetHeight).toString() + 'px';
f.style.width = Math.max(f.offsetWidth, t.offsetWidth).toString() + 'px';
setTimeout(function(){mBlockChange = false}, 100);
}
//This one for IE9+, FFox, Chrome and Safari
//http://help.dottoro.com/ljrmcldi.php
function bindEvents(){
var tA = document.getElementById('A');
var tB = document.getElementById('B');
//The addEventListener() method is not supported in Internet Explorer 8 and earlier versions with resize.
//Resizing the body
document.body.onresize = function(){
//We only do this once the resizing is actually finished.
if (this.Timer) clearTimeout(this.Timer);
this.Timer = setTimeout(function(){
//console.log('Resize', this);
equalSize()
}, 300)
};
//If supported, we listen on dom changes.
if ('MutationEvent' in window){
document.addEventListener('DOMSubtreeModified', function(){
if (document.Timer) clearInterval(document.Timer);
//console.log('DOMSubtreeModified', this);
if (!mBlockChange) equalSize()
}, false);
}
//We set an interval for browsers which do not support DOMSubtreeModified
//If you do not want to rely on ('MutationEvent' in window) put it out of else and cancel the timer (scenario B)
//Can not bind parameters to setInterval in IE8- :s
else{
document.Timer = setInterval(function(){
//console.log('Interval', 'Document');
equalSize()
}, 1000);
}
}
</script>
</head>
<body onload = 'bindEvents()'>
<div id = 'A'><p contenteditable = 'true'>A</p></div>
<div id = 'B'><p contenteditable = 'true'>B</p></div>
</body>
</html>
https://jsfiddle.net/5cn7maqe/
Yet your elements height and width should not magically change, it always requires some interactions, like changing dom by ajax, oninput with contenteditable or resizing the window. You would be better off to just adjust it after those actions manually.
Edit: Made some minor changes.
https://jsfiddle.net/5cn7maqe/1/
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();
}
});
});
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/
I want to animate an image from 200 x 300px to its original size using jQuery.
I have this picture:
var imgHtml = "<img id='bigImg' src='" + bigSrc + "' alt='' style=\"height:200px; width:300px\"/>";
$("#divId").html(imgHtml);
And this jQuery code:
$("#bigImg").animate({
height: "400px",
width: "600px",
},500);
It works well, but I actually have to hardcode the future size. I would like to animate to the original size.
How can I do this ?
Try doing this
HTML
<div id="divId">Loading</div>
<input id="submit" type="button" value=" Click Me " />
JavaScript
var bigSrc = "Image Source";
var img = new Image(),
oWidth, oHeight;
img.onload = function() {
oWidth = this.width;
oHeight = this.height;
this.width = 300;
this.height = 200;
this.id = "bigImg";
}
img.src = bigSrc;
$("#submit").click(function(e) {
$("#divId").append(img);
$("#bigImg").animate({
height: oHeight,
width: oWidth,
}, 500);
});
Check this demo jsFiddle
You can tweak to suit you. Hope this helps you.
Okay, I see what you mean now.
$("#bigImg").width() will return the width in px, and height will do similar. You can also use .outerWidth() and .innerWidth() to include padding/border or just padding, respectively.
From your code, you've already changed the original dimensions of the image by using inline styles. Instead, save the image dimensions, change the image to 200 x 300px in jQuery, do what you want to it, then change it back to original dimensions:
var originalWidth = $("#bigImg").width();
var originalHeight = $("#bigImg").height();
$("#bigImg").css({
width: '200px',
height: '300px'
});
//Do whatever you meant to do here, the when you're finished...
$("#bigImg").animate({
width: originalWidth,
height: originalHeight,
},500);
jQuery documentation:
http://api.jquery.com/animate/ or http://api.jquery.com/category/dimensions/