Need help setting div in table height using Javascript - javascript

I am trying to set the div to a certain height inside an empty table cell to set the cell to 100% height. (The whole page consists of just the table with no padding.)
Here is some relevant code:
<table border="0" width="100%">
<tr>
<td class="boxmiddleleft"></td>
<td class="boxmiddlecenter"><script language="javascript" src="includes/clock.js">/*clock*/</script></td>
</tr>
<tr>
<td class="boxbottomleft"><script language="javascript" src="includes/windowsize.js"></script><div id="divbottomresize"></div></td>
<td class="boxbottomcenter"><button type="button" onclick="resizeheight();">Changed the window height? Reset by pressing this button.</button></td>
</tr>
</table>
(With the div im trying to change height called '#divbottomresize')
And the JavaScript I am using for this:
var element = "divbottomresize";
function resizeheight(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop) + "px");
}
If you have any idea what I am doing wrong please could you tell me. Alternatively if you find other code that does what I want feel free to paste or link me. (I do not want to use jQuery if possible.)
When I run the code in Chrome and go to 'Inspect Element' I get the error:
windowsize.js:12Uncaught TypeError: Cannot read property 'style' of undefined on the line element.style.height = ((height - element.offsetTop) + "px");
EDIT: I have changed var element = "divbottomresize"; to var element = document.getElementById("divbottomresize"); as someone helpfully suggested. This still does not work and I get the same error and no height change.

The resize function requires the element parameter, so we need to update the HTML:
<td class="boxbottomcenter"><button type="button" onclick="resizeheight('divbottomresize');">Changed the window height? Reset by pressing this button.</button></td>
Now, we need to change the Javascript, to use the STRING value passed by the function and then retrieve the tag with that ID for further processing:
function resizeheight(id_element) {
var div = document.getElementById(id_element);
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
div.style.height = ((height - div.offsetTop) + "px");
}

Related

Clear out previous value when new value displays

I've been creating this simple program to calculate screen width and height when resizing page. It gives the width and height of the page on load as the default but each time I resize it a new value gets displayed along with the previous one. I want only to display the new value. How can I do that?
Here's the HTML
<body onload="getSize()" onresize="getSize()">
<div id="wh">
<!-- Place height and width size here! -->
</div>
Here's the JS
function getSize(){
let w = window.innerWidth;
let h = window.innerHeight;
let displayThis = "Width is " + w + " and height is " + h;
display.append(displayThis);
}
display.append(displayThis); means to add text after previous text, if you want to replace previous one,use this:
display.innerHtml = displayThis
this just replace element's inner html everytime, just keey the final one.

jQuery each() function not working after if/else statement has been completed for both if and else outputs

I am using jQuery & javascript to switch the classes for images based on whether the viewport width is less than or greater than twice the width of the image.
I am using $(window).resize to detect when the widow is resized and then the each() function to iterate through all images of a certain class.
An if statement checks whether the width of the viewport is less than twice the width of the image and if so removes one class and adds another. The else statement does the reverse.
One page load it works fine for as many widow width changes as I do, until both the if and the else have been executed, then they stop working. Any suggestions would be greatly appreciated!
Thanks
Here's my code:
function updateViewportDimensions() {
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName("body")[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight || e.clientHeight || g.clientHeight;
return { width: x, height: y };
};
jQuery(window).resize(function() {
var viewport = updateViewportDimensions();
var viewport_width = viewport['width'];
console.log('Viewport width = ' + viewport_width);
jQuery(document).ready(function($) {
$('.alignright').each(function(i, obj){
// get the width of each image
var image_width = $(this).width();
// if the viewport width is less than twice the image width then switch the classes
if(viewport_width < (image_width * 2)) {
$(this).removeClass('alignright');
$(this).addClass('aligncenter');
console.log('Viewport is less than twice image width');
} else {
console.log('Viewport is more than twice image width');
$(this).addClass('alignright');
$(this).removeClass('aligncenter');
};
});
});
});
If I am reading this correctly, (this).removeClass('alignright'); is changing your dom. Because of this all the link to the class alignright is now new but your jquery is still looking for the instances that have been removed.
Update $('.alignright').each(function(i, obj){ to be one level higher than what is being altered.
if the code is
<div id="outer-wrapper">
<div class="alignright">
content
</div>
</div>
use $('#outer-wrapper .alignright').each(function(i, obj){

Equivalent to setting html and body height to window height in vanillajs

What is the equivalent code in vanilla js to this line of javascript?
$('html, body, #wrapper').height($(window).height());
This was my attempt, but it doesn't seem to be working properly (it seems to not set any height on all 3 elements at all):
var w=window,d=document,
e=d.documentElement,
g=d.getElementsByTagName("body")[0];
x=w.innerWidth || e.clientWidth || g.clientWidth,y=w.innerHeight || e.clientHeight || g.clientHeight;
document.querySelector("html").clientHeight = g.clientHeight = document.getElementById("wrapper").clientHeight = y;
You can get the height of the window using Window#innerHeight, select the target using Document#querySelectorAll. To iterate the elementList that querySelectorAll returns, we'll use NodeList#forEach (if not supported convert the element list to an array - see below), and set the height on each element:
var height = window.innerHeight + 'px';
document.querySelectorAll('html, body, #wrapper').forEach(function(el) {
el.style.height = height;
});
#wrapper {
background: red;
}
<div id="wrapper"></div>
If you need to convert the the element list to an array:
[].slice.call(document.querySelectorAll('html, body, #wrapper'), 0)
or
Array.from(document.querySelectorAll('html, body, #wrapper'))

Javascript does not continue after adding stylesheet to a class

I want to display a div container if the device has a special width. I made a simple if-condition and it is working well.
I wanted to add a second function to my code and the function was not called. After trying out I saw that the code stops after the document.getElementyById-Code.
If the alert("Hello World") is called in the if-condition before the getElementById, it is called. If it is called in the if-condition after the getElementById, it is not called anymore.
Why is the progress stuck there?
The console output:
[Error] TypeError: null is not an object (evaluating 'document.getElementById("whitecontainer").style')
setHeightandWidth (-Link deleted-, line 402)
onresize (-Link deleted-, line 382)
but the object cannot be null, because the style change does work, it is just stuck after doing the resize.
Thanks for help!
function setHeightandWidth() {
var body = document.body,
html = document.documentElement;
var height = (Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight) - 75 - 248);
var width = document.body.clientWidth;
if (width < 1199) {
document.getElementById("whitecontainer").style.display = "none";
alert("Hello World!");
}
if (width >= 1199) {
width = 1140;
document.getElementById("whitecontainer").style.display = "inherit";
}
var white_container = document.getElementById("whitecontainer");
white_container.style.height = height + "px";
white_container.style.width = width + "px";
}
Problem is in this line
document.getElementById("whitecontainer").style.display
javascript is unable to find id "whitecontainer" tat's why it throws an null exception and script breaks
The alert not working probably means that the line before it caused an error.
Do the lines
white_container.style.height = height + "px";
white_container.style.width = width + "px";
Run?
I have a feeling your code fails everytime you use document. XXXXXX
'whitecontainer' is probably not a real element

How to make a function set css width with a JavaScript variable?

I have this code:
...<script>
function handleSize()
{
var setObjectSize=window.innerWidth - 600;
document.getElementById("spin").style.width=setObjectSize + "px";
document.getElementById("spin").style.height=setObjectSize + "px";
}
</script>
</head>
<body>
<section id="spin" onLoad="handleSize()">...
All I am trying to do is to create a function that will set the height and width of the element according to window size using a formula and make sure height and width are the same. I am very new to javascript (almost know nothing about it), so despite there being a ton of example of such questions, and me following them, I can't get this code to work. What am I doing wrong?
The problem that I'm seeing, is that the onload event for the section tag isn't firing. You should add your javascript as a self-executing anonymous function to the end of your body tag and this will work for you.
<body>
<section id="spin" style="border:5px solid black;"></section>
<script>
(function () {
var setWindowSize = window.innerWidth - 600;
document.getElementById("spin").style.width = setWindowSize + "px";
document.getElementById("spin").style.height = setWindowSize + "px";
})();
</script>
</body>
See Here for a demo: http://jsfiddle.net/T7DW6/
You should move onload to the body tag:
<body onLoad="handleSize()">
<section id="spin">...
I would suggest you to use jQuery, that is JavaScript library used world wide. So in order to develop it using jQuery you need to do next
function setElementSize(elId) {
var _w $(window); //to get instance of window
var _el $('#' + elId); //jquery to get instance of element
var _width = _w.width();
var _height = _w.height();
//set width=height
if(_height>_width)
{
_height = _width;
} else { _width = _height; }
_el.css({
width: _width,
height: _height
});
}
//this will execute script when document is loaded.
$(document).ready(function(){
setElementSize('spin');
});
Function above will set width and height of element to match window size. If height > width then it will use width as width & height otherwise it will use height.
I assume that you want to change this automatically if window is resized then do this
$(window).resize(function(){
setElementSize('spin');
});
The onload event occurs when an object has been loaded.
onload is most often used within the element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
onload is only Supported by the Following HTML Tags:
body, frame, frameset, iframe, img, input type="image", link, script, style
from here: event_onload
then a is may be not the best here (height and weight does not change anything, you should use a div.
In order to know, the one to use, please read this:
what-is-the-difference-between-section-and-div
I try your exam and it works fine. The only thing that i changed was the way that you call the function
function handleSize(){
var setWindowSize=window.innerWidth - 600;
document.getElementById("spin").style.width=setWindowSize + "px";
document.getElementById("spin").style.height=setWindowSize + "px";
}
window.onload = function () {
handleSize();
}
I think that onLoad="handleSize()" have to be onload="handleSize()" but don't use that way because it is not a good practise!
this works for me
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button and watch it grow.</p>
<button id = "myButton" onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var w = window.innerWidth;
var h = window.innerHeight;
var x = document.getElementById("myButton");
x.style.width = w + "px";
x.style.height = h + "px";
}
</script>
</body>
</html>

Categories