Javascript does not continue after adding stylesheet to a class - javascript

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

Related

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){

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>

jQuery window width not equal to CSS's window width

I'm using the following two pieces of CSS and JS code:
#media (max-width: 720px) {
// a code to make arrows in a carousel disappear
}
if(jQuery(window).width() <= 720){
// a code to make arrows in the carousel stop working
}
The problem with them is that the latter executes on exactly width=738px and not 720px. I suspect that this is because of browser's vertical scrollbar that has width equal to 18px in Chrome.
Is there a way to unify this? I'd like these actions to happen at the same moment in all browsers regardless of the scrollbar's width.
Tests (when browser is # 720px and CSS has already executed):
jQuery(document).innerWidth() = 703
jQuery(window).innerWidth() = 703
jQuery(document).width() = 703
jQuery(window).width() = 703
jQuery('body').width() = 703
jQuery('html').width() = 703
I had to tackle the same problem a while ago, and so far the most correct solution I found is to use media queries to pass the actual window size to Javascript. You have to follow these steps:
Add a hidden element to your page,
Use media queries to alter the max-width property of that element,
Read back the max-width property of that element through Javascript.
For instance, add the following element to your page:
<div id="currentMedia"></div>
Then write the following CSS rules:
#currentMedia {
display: none;
}
#media (max-width: 720px) {
/* Make arrows in the carousel disappear... */
#currentMedia {
max-width: 720px;
}
}
Then, from the Javascript side, you can write:
if (parseInt(jQuery("#currentMedia").css("max-width"), 10) <= 720) {
// Make arrows in the carousel stop working...
}
And it will be accurate regardless of the scrollbar size, since the value comes from the same media query that triggers the carousel's disappearance.
I tested this solution on all major recent browsers, and it gives correct results.
You will find the big summary of what properties are supported on what browsers on this page on quirksmode.org.
Your best bet is probably to grab an element in the page (using document.body where supported, or document.getElementById or whatever), walk its offsetParent chain to find the topmost element, then examine that element's clientWidth and clientHeight.
innerWidth documentation
innerWidth() says this method is not applicable to window and document objects; for these, use .width()
try
How can I get the browser's scrollbar sizes?
From Alexandre Gomes Blog
function getScrollBarWidth () {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild (inner);
document.body.appendChild (outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
document.body.removeChild (outer);
return (w1 - w2);
};
in your code
if(jQuery(window).width()-getScrollBarWidth(); <= 720){
// a code to make arrows in the carousel stop working
}
A bit outdated thread, but i've found this solution
function getWidth(){
return ((window.innerWidth > 0) ? window.innerWidth : screen.width);
}
If you are using Bootstrap > 3 then I will suggest you something.
Bootstrap ships with .container class in its Css and predefined. And its altering with #media queries.So my working code sample for this is below.
function detectWidth(){
var width = $('.container').eq(0).outerWidth() ;
console.log(width);
if(width<750){
// do something for XS element
}else if(width>=750 && width<970){
// do something for SM element
}else if(width>=970 && width<1170){
// do something for MD element
}else{
// do something for LG element
}
}
I realize this is an old thread, but I think it can still benefit from this answer.
var width = window.outerWidth;
This will give you the width of the window including scrollbars, which is what media queries use, I believe.

Modify external CSS values

Hi I am trying to dynamicly change the height of a division using JavaScript but I can only get the JS to read the Height element of the div if it defined using style tags inside the HTML mark-up.
If its in a separate sheet it returns NaN, I'm assuming because it can't find a value and is actually returning null (I'm using ParseInt to make it work).
Here is the HTML:
<div id="dropdown_container">
<div id="dropdown" style="height:100px;">
a
</div>
</div>
(Wish the HTML stlye markup)
And here is the JS:
function clickDown() {
var el = document.getElementById('dropdown');
var maxHeight = 200;
getHeight = parseInt(el.style.height.substring(0,(el.style.height.length)-2));
console.log(getHeight);
getHeight += 2;
el.style.height = getHeight + 'px';
timeoutHeightInc = setTimeout('clickDown()',15);
if(getHeight >= maxHeight){
clearTimeout(timeoutHeightInc);
}
}
Does anyone know of a reason for this (mis?)functionaility. And a solution for it?
Here is a jsFiddle.
Try moving the height over to the CSS to see the issue i'm having.
ParseInt is missing it's radix.
You say:
I can only get the JS to read the Height element of the div if it
defined using style tags inside the HTML mark-up
Now you are only reading the div's attribute style. Which you set inline. So if you remove that, than you can not read it anymore. Make sense?
You want to get the computed height. Try: .offsetHeight
Basis of test-case to play with inc. fixed radix. this fiddle
UPDATE: tada: fixed, see this updated fiddle
function clickDown() {
var el = document.getElementById('dropdown');
var maxHeight = 200;
getHeight = parseInt(el.offsetHeight,10);
console.log(getHeight);
getHeight += 2;
el.style.height = getHeight + 'px';
timeoutHeightInc = setTimeout('clickDown()',15);
if(getHeight >= maxHeight){
clearTimeout(timeoutHeightInc);
}
}

Need help setting div in table height using 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");
}

Categories