margin-left undefined after setting with jQuery - javascript

I am trying to set the margin of my wrapper dynamically. Here is my JavaScript code:
var w = window.innerWidth;
if (w > 800) {
var margin = (w - 800) / 2;
$('.ui-page').css('margin-left', margin);
var output = $('.ui-page').css('margin-left');
$('.ui-footer').css('margin-left', margin);
$('.ui-header').css('margin-left', margin);
alert(output);
}
But when I open the page, the alert says undefined !?

In addition to my previous answer, which shows it working, there is this fail-safe.. this is a different approach that must always work. I suspect your page is not loaded when the code is run:
http://jsfiddle.net/digitalextremist/xfVdL/1/
$( document ).ready( function() {
var w = window.innerWidth;
var maxWidth = 300
if ( w > maxWidth ) {
var margin = (w - maxWidth) / 2;
$('.ui-page').css('margin-left', margin);
var output = $('.ui-page').css('margin-left');
$('.ui-footer').css('margin-left', margin);
$('.ui-header').css('margin-left', margin);
alert( output );
}
});
Or, if you use jQuery Mobile:
$( document ).on( 'pagebeforeshow', function( event ) {
var w = window.innerWidth;
var maxWidth = 300
if ( w > maxWidth ) {
var margin = (w - maxWidth) / 2;
$('.ui-page').css('margin-left', margin);
var output = $('.ui-page').css('margin-left');
$('.ui-footer').css('margin-left', margin);
$('.ui-header').css('margin-left', margin);
alert( output );
}
});
It is critical that you let the page load first before testing sizes as you are doing.
What you are doing is correct, but jQuery and jQuery Mobile render the page in stages. To make sure you take your measurement of .ui-page at the right time, once everything is properly loaded by jQuery or jQuery Mobile, you need to make sure it all rendered first, which means you need to use $( document ).on( 'pagebeforeshow' ) for jQuery Mobile, or $( document ).ready() for jQuery itself. These make sure your code runs after the page is fully rendered. Before that, your measurements will be wrong! And before that, .ui-page might not even exist yet, if it is added by jQuery Mobile.
Here is more information for you:
When should I use jQuery's document.ready function?
jQuery: Why use document.ready if external JS at bottom of page?
http://learn.jquery.com/about-jquery/how-jquery-works/
http://www.w3schools.com/jquerymobile/event_pagebeforeshow.asp
http://jquerymobile.com/demos/1.1.0/docs/api/events.html

Try setting the margin with a unit; something like:
$('.ui-page').css('margin-left', margin + 'px');
Also, you can use margin: 0 auto; to have your div's center themselves within the page. See MDN for some details.

It looks like your query for .ui-page is returning no elements.
Therefore, when trying to retrieve the margin-left property, it returns undefined.
Try checking whether whether .ui-page actually exists on the page.
A quick way to do this:
if ( $('.ui-page').length > 0 ) alert('.ui-page exists!');

What version of jQuery are you using? And what browser?
Without changing your code really at all, it works fine under version 1.10.1
( It also works under every other version... on Chrome and Firefox )
See what I mean? http://jsfiddle.net/digitalextremist/xfVdL/
So, it does work... No "px" required.

Related

Get constant browser height and width

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.

jQuery function on window events (load and resize)

I'm not sure how to use the order of the window events load and resize on jQuery to make it work when resizing. The first function is used to get the total width except the scrollbar width, because the CSS is using the device width, but the JS is using the document width.
The second function adds a style when the total screen width is between 768px and 1024px, and it should work when I load the page at any screen, after resizing, etc. I'm doing a lot of tests and I think the problem is about the window events order.
For being more specific about the problems, it doesn't remove the style when I load the page at 900px and I expand it to > 1024px! Or by the contrary, it doesn't add the style when I load the page at 1300px and I shorten the width to 900px.
I think it's 'cause of the load and resize events order, but I'm not totally sure. Or maybe I'm not doing the correct declaration of the variable into the resize.
The code:
function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
$(document).ready(function(){
var vpwidth=$(window).width();
$(window).on('resize', function(){
var changeWidth = (($('.main-content .wrap').width() * 96.3)/100) - 312;
if(vpwidth >= 768 && vpwidth <= 1024) {
$('.contentleft, .contentright').css('width', changeWidth + 'px');
} else {
$('.contentleft, .contentright').removeAttr('style');
}
}).resize();
});
I believe the issue is that you're not re-calculating the vpwidth on resize, So the value you got when the page was loaded will be used every time window is resized.
try
$(document).ready(function(){
$(window).on('resize', function(){
var vpwidth=$(window).width(); // get the new value after resize
var changeWidth = (($('.main-content .wrap').width() * 96.3)/100) - 312;
if(vpwidth >= 768 && vpwidth <= 1024) {
$('.contentleft, .contentright').css('width', changeWidth + 'px');
} else {
$('.contentleft, .contentright').removeAttr('style');
}
}).resize();
});
The issue is because you are not recalculating the width (vpwidth) on resize function.
It is initialized and set on page load itself and hence doesn't change when the window is resized causing the style to not be added or removed.
You need to re-assign the value to the variable from within the resize function.
$(window).on('resize', function(){
var vpwidth=$(window).width();
}
Demo Fiddle

Jquery .height() not working until resize of window

I'm using this code to resize a div on my page:
function sizeContent() {
var newHeight = ($("html").height() - $(".header").height() -3) + "px";
$(".content").height(newHeight);
}
I am triggering this using:
$(window).resize(sizeContent());
But I also call it inside
$(document).ready(sizeContent());
to set all the heights properly.
If i resize the browser window by dragging at its borders it works great.
But the initial call does not seem to have any effect. Putting an alert inside the sizeContent function I can see that it is being called at page ready, and is setting the right height, but nothing is changed on the page.
It's as if the browser does not recognize that it needs to redraw anything unless the window itself is changed.
Solved:
In the end it was not the javascript that was the problem, using div's with display:table and display:table-row was causing it. Removed these from the css and everything worked.
// If you put your code at the bottom of the page to avoid needing`$(document).ready`, it gets even simpler:
$(window).on('resize', function () {
var newheight = ($(window).height() - $('.header').height() - 3);
$(".content").css("height", newheight);
}).trigger('resize');
// Another way to do that same thing
$(document).ready(sizeContent);
$(window).on('resize', sizeContent);
function sizeContent() {
var newheight = ($(window).height() - $('.header').height() - 3);
$(".content").css("height", newheight);
}
// Another technique is to`.trigger()`one event inside the other:
$(window).on('resize', function () {
var newheight = ($(window).height() - $('.header').height() - 3);
$(".content").css("height", newheight);
});
$(document).ready(function () {
$(window).trigger('resize');
});
Replace
$(".content").css({height:newHeight}) //replace this
with
(".content").height(newHeight);
Use below code:
function sizeContent() {
var newHeight = ($(window).height() - $(".header").css('height')-3) ;
$(".content").css('height',newHeight);
}

Resize iframe to content with Jquery

I'm trying to resize an iframe dynamicly to fit its content. To do so I have a piece of code:
$("#IframeId").height($("#IframeId").contents().find("html").height());​
It doesnt work. Is it because of cross-domain issue? How do I get it to fit? Please take a look at Fiddle: JsFiddle
ps I have set the html and body of the link height:100%;
You just need to apply your code on the iframe load event, so the height is already known at that time, code follows:
$("#IframeId").load(function() {
$(this).height( $(this).contents().find("body").height() );
});
See working demo . This demo works on jsfiddle as I've set the iframe url to a url in the same domain as the jsfiddle result iframe, that is, the fiddle.jshell.net domain.
UPDATE:
#Youss:
It seems your page for a strange reason don't get the body height right, so try using the height of the main elements instead, like this:
$(document).ready(function() {
$("#IframeId").load(function() {
var h = $(this).contents().find("ul.jq-text").height();
h += $(this).contents().find("#form1").height();
$(this).height( h );
});
});
Not sure why #Nelson's solution wasn't working in Firefox 26 (Ubuntu), but the following Javascript-jQuery solution seems to work in Chromium and Firefox.
/**
* Called to resize a given iframe.
*
* #param frame The iframe to resize.
*/
function resize( frame ) {
var b = frame.contentWindow.document.body || frame.contentDocument.body,
cHeight = $(b).height();
if( frame.oHeight !== cHeight ) {
$(frame).height( 0 );
frame.style.height = 0;
$(frame).height( cHeight );
frame.style.height = cHeight + "px";
frame.oHeight = cHeight;
}
// Call again to check whether the content height has changed.
setTimeout( function() { resize( frame ); }, 250 );
}
/**
* Resizes all the iframe objects on the current page. This is called when
* the page is loaded. For some reason using jQuery to trigger on loading
* the iframe does not work in Firefox 26.
*/
window.onload = function() {
var frame,
frames = document.getElementsByTagName( 'iframe' ),
i = frames.length - 1;
while( i >= 0 ) {
frame = frames[i];
frame.onload = resize( frame );
i -= 1;
}
};
This continually resizes all iframes on a given page.
Tested with jQuery 1.10.2.
Using $('iframe').on( 'load', ... would only work intermittently. Note that the size must initially be set to 0 pixels in height if it is to shrink below the default iframe height in some browsers.
What you can do is the following:
Within the iFrame use document.parent.setHeight(myheight) to set the height within the iFrame to the parent. Which is allowed since it is a child control. Call a function from the parent.
Within the parent you make a function setHeight(iframeheight) which resizes the iFrame.
Also see:
How do I implement Cross Domain URL Access from an Iframe using Javascript?
Just do it on the HTML tag, works perfect
$("#iframe").load(function() {
$(this).height( $(this).contents().find("html").height() );
});
As the answer to the question use an already outdated jquery (load has been deprecated and replaced with .on('load',function(){}), below is the latest code for the answer in the question.
Note that I use the scrollHeight and scrollWidth, which I think will load much nicer than using Height and Width like the answer provided. It will totally fit, without scroll anymore.
$("#dreport_frame").on('load',function(){
var h = $('#dreport_frame').contents().find("body").prop('scrollHeight');
var w = $('#dreport_frame').contents().find("body").prop('scrollWidth');
$('#dreport_frame').height(h);
$('#dreport_frame').width(w);
})
Adjust height of an iframe, on load and resize, based on its body height.
var iFrameID = document.getElementById('iframe2');
var iframeWin = iFrameID.contentWindow;
var eventList = ["load", "resize"];
for(event of eventList) {
iframeWin.addEventListener(event, function(){
if(iFrameID) {
var h = iframeWin.document.body.offsetHeight + "px";
if(iFrameID.height == h) {
return false;
}
iFrameID.height = "";
iFrameID.height = iframeWin.document.body.offsetHeight + "px";
}
})
}
At end, I come with this cross-domain solution that work also for resize...
(resize not triggering : Auto resize iframe height when the height of the iframe contents change (same domain) )
Iframe :
(function() {
"use strict";
var oldIframeHeight = 0,
currentHeight = 0;
function doSize() {
currentHeight = document.body.offsetHeight || document.body.scrollHeight;
if (currentHeight !== oldIframeHeight) {
console.log('currentHeight', currentHeight);
window.parent.postMessage({height:currentHeight}, "*");
oldIframeHeight = currentHeight;
}
}
if (window.parent) {
//window.addEventListener('load', doSize);
//window.addEventListener('resize', doSize);
window.setInterval(doSize, 100); // Dispatch resize ! without bug
}
})();
Parent page :
window.addEventListener('message', event => {
if (event.origin.startsWith('https://mysite.fr') && event.data && event.data.height) {
console.log('event.data.height', event.data.height);
jQuery('#frameId').height(event.data.height + 12);
}
});

How to change the height of div with the content of other div

I have two div in my website page one beside the other(one left and one right),I want to change the height of the left one with the content of the right one using javascript
I tried to have the dynamic height of the right div :
function getHeight() {
var doc = document.getElementById('div.right');
if (document.all) // ok I.E
{
H = doc.currentStyle.height;
}
else // ok FF
{
H = document.defaultView.getComputedStyle(doc, null).height;
}
}​
But I stopped here because I don't know how to pass the javascript variable to my page of style CSS,I mean I dont know how to apply this value in the other div(left div) in the same page automatically.
Any Idea?
Just use
document.getElementById('div.left').style.height = H;
Edit
AFAIK you cant modify an external stylesheet from javascript
Is the height of the div determined at the time the document is served, loaded or or any arbitrary time after the document has loaded?
The code I suggested above was to be used like this(I'm assuming your IE code is correct)
function getHeight() {
var doc = document.getElementById('div.right');
if (document.all) // ok I.E
{
H = doc.currentStyle.height;
}
else // ok FF
{
H = document.defaultView.getComputedStyle(doc, null).height;
}
document.getElementById('div.left').style.height = H;//✔
}
Just to help people I found a great code to change the height of two div autoamtically using a little of Jquery :
<script type='text/javascript'>
$(window).load(function(){
var lh = $('#div.right').height();
var rh = $('#div.left').height();
if (lh >= rh){
//alert('left : ' + lh);
$('#div.left').height(lh);
} else {
//alert('right : ' + rh);
$('#div.right').height(rh);
};
});
</script>
It's works for all navigators.

Categories

Resources