Resizing an image using Javascript running in Opera Browser - javascript

I hope someone can help with this quirky issue I am having with the Opera Browser, I have version 11 Beta installed, but I suspect is a common problem in Opera.
The website and page in question is http://www.amigaos.net/index.html.
At the bottom of the body of the html I have the following code which resizes the 3 images you see on this webpage depending on width of the viewport at page load. In Safari and FireFox the code works fine, but in Opera the following lines which involve resizing the width and height of an image do not work:
document.getElementById('img1').width = '475';
document.getElementById('img1').height = '375';
Here is the code in full (sorry, about the layout, stackoverflow hasn't formatted carriage returns correctly)
<script type="text/javascript">
function GetWidth()
{
var x = 0;
if (typeof window.innerWidth != 'undefined')
{
x = window.innerWidth;
}
else if (document.documentElement && document.documentElement.clientHeight)
{
x = document.documentElement.clientWidth;
}
else if (document.body)
{
x = document.getElementsByTagName('body')[0].clientWidth;
}
return x;
}
width = GetWidth();
if (width>=1680)
{
document.getElementById('img1').width = '475';
document.getElementById('img1').height = '375';
document.getElementById('img2').width = '475';
document.getElementById('img2').height = '375';
document.getElementById('img3').width = '475';
document.getElementById('img3').height = '375';
}
else if ((width>800) && (width<=1280))
{
document.getElementById('img1').width = '300';
document.getElementById('img1').height = '235';
document.getElementById('img2').width = '300';
document.getElementById('img2').height = '235';
document.getElementById('img3').width = '300';
document.getElementById('img3').height = '235';
}
else if (width<=800)
{
document.getElementById('img1').width = '225';
document.getElementById('img1').height = '195';
document.getElementById('img2').width = '225';
document.getElementById('img2').height = '195';
document.getElementById('img3').width = '225';
document.getElementById('img3').height = '195';
}
</script>

instead of doing width and height attributes, I think you can just set width: 33% via CSS and have the scaling happen automatically, regardless of the browser window size. Better solution than trying to use javascript, IMHO.
Here's a simple tutorial: http://haslayout.net/css-tuts/CSS-Proportional-Image-Scale

you are making this way too complicated. I don't think your issue is browser-specific, you just need to recode your script.
First. I would recommmend using percentages.. Not sure how you will guess the visitors browser width in pixels.
Let's say that your three resizeable images are 20% width of your browser. So your css would be:
#img1, #img2, #img3 {
width: 20%;
}
now that your css says that your images are 20% of the total with, you're good to add some js. Keep in mind that the percentage will be that of its outer container.
<script type=text/javascript">
function resizeImages() {
document.getElementById('img1').style.height = (document.body.clientHeight - 100) * 0.2;
document.getElementById('img2').style.height = (document.body.clientHeight - 100) * 0.2;
document.getElementById('img3').style.height = (document.body.clientHeight - 100) * 0.2;
}
</script>
and most importantly.. call your function:
add this to your body tag:
<body onresize="resizeImages()">
boom.. you're done.

Related

How does this page detect movement of a desktop browser window?

In messing around with some DeviceOrientation stuff, I came across this page.
When you shake the browser, the site reacts! What API is being used here where the browser movement is detected? I notice it works in the latest versions of Safari, Firefox and Chrome.
I don't see any mention of this in the DeviceOrientation docs, nor on three.js...
They use the window.screenX/screenY properties to get browser window position and window.innerWidth/innerHeight to get window's size.
The Window.screenX read-only property returns the horizontal distance, in CSS pixels, of the left border of the user's browser viewport to the left side of the screen.
The below function is used in that code:
function getBrowserDimensions() {
var changed = false;
if (stage[0] != window.screenX) {
delta[0] = (window.screenX - stage[0]) * 50;
stage[0] = window.screenX;
changed = true;
}
if (stage[1] != window.screenY) {
delta[1] = (window.screenY - stage[1]) * 50;
stage[1] = window.screenY;
changed = true;
}
if (stage[2] != window.innerWidth) {
stage[2] = window.innerWidth;
changed = true;
}
if (stage[3] != window.innerHeight) {
stage[3] = window.innerHeight;
changed = true;
}
return changed;
}
use screen.orientation property.
reference

$(window).resize not firing function properly on height/width condition

I have a fixed-positioned full-screen image gallery. The container div height is set via jQuery, and the next div (#page) has a margin-top equal to window.height.
Here is this code:
var windowH = $(window).height();
var windowW = $(window).width();
function marginTop() {
var currentH = $(window).height();
$("#page").css("margin-top", currentH +'px');
$("#image-gallery").css("height", currentH +'px');
console.log('mTop fired!');
};
$(window).resize(function() {
var newH = $(window).height(); // Records new windows height after resize
var newW = $(window).width();
var maxH = windowH + 90; // Sets a positive delta of some px
var maxW = windowW + 60;
var minH = windowH - 90; // Sets a negative delta of some px
var minW = windowW - 60;
if(newH > maxH) { // If the height difference is more than 50px, then set new marginTop for #page
marginTop();
console.log('fire for bigger height');
} else if(newH < minH) {
marginTop();
console.log('fire for smaller height');
} else if(newW > maxW) {
marginTop();
console.log('fire for bigger width');
} else if(newW < minW ) {
marginTop();
console.log('fire for smaller width');
}
});
I've split the conditions in several else if statement because it didn't work fine, and I had to check out when it was working, when not.
The various if...elseif...elseif... solve a problem on mobile browsers: without that delta, the #image-gallery div would change dimension when the address bar appears or disappears, resulting in stuttering adjustments of the div's height. Moreover, i did not want to redraw the whole thing for small changes in viewport on desktop too.
However it has some problem, as it doesn't work correctly. In particular:
marginTop() is fired only for window.resize with smaller height (checked from console.log)
on desktop, if the window is resized through the top-right-corner button, it doesn't fire at all.
removing all the if-else-if conditions, it works fine on desktop in any situation (but the address-bar is still a problem on mobile)
Can't figure it out, the code seems fine to me, but not to browsers. Where's the catch?
Tested on Firefox and Chrome latest
There's a host of small problems here. Your if statement, as is, will never reach the width compares. First of all, with the width being in a if else with the height, then height is always evaluated first and width is never hit if height is adjusted.
Next, your "current height|width" as seen at var windowH = $(window).height(); is never reset. This means, if the user show up with a viewport (say browser is minimized) of 200:150, then height:width will always be measured based on 200:150. This would make for a very different experience from someone using a much larger viewport.
Another issue, often found with window re-sizing, is the multiple amount of times your code will fire. This can cause major issue with overlapping commands, thus causing double feedback.
Below is how I would handle this and a suggested rebuild.
/* simple method to get the current window size as an object where h=height && w=width */
function getWindowSize() {
return { h: $(window).height(), w: $(window).width() };
}
function doWork(typ, msg) {
// report msg of change to console
console.log(typ == 'h' ? 'HEIGHT:\t' : 'WIDTH:\t', msg);
// we really only need fire your method if height has changed
if (typ == 'h') marginTop();
// a change was made, now to reset
window.sizeCheck = getWindowSize();
}
// your original method
// brokered off so it can be used independently
function marginTop() {
var currentH = $(window).height();
console.log('currentH', currentH)
$("#page").css("margin-top", currentH +'px');
$("#image-gallery, #page").height(currentH);
console.log('mTop fired!');
}
/* action area for window resize event */
function windowResize() {
// made my variables short and sweet,
// sch=sizeCheck, scu=sizeCurrent
var sch = window.sizeCheck, // get previously set size
scu = getWindowSize(),
maxH = sch.h + 90,
minH = sch.h - 90,
maxW = sch.w + 60,
minW = sch.w - 60;
if (scu.h > maxH) doWork('h', 'View Got <b>Taller</b>');
else if (scu.h < minH) doWork('h', 'View Got <i>shorteR</i>');
// for what you want, the following isn't even really nec
// but i'll leave it in so you can see the work
if (scu.w > maxW) doWork('w', 'View Got <b>Wider</b>');
else if (scu.w < minW) doWork('w', 'View Got <i>thinneR</i>');
}
$(function() {
// ezier to maintain one global variable than to scope
// shot 2 which could easily be overriden in a latter method,
// by simple confusion
window.sizeCheck = getWindowSize();
// call of event to establish correct margin for the page div
marginTop()
$(window).resize(function(e) {
// this will clear our timer everytime resize is called
if (this.tmrResize) clearTimeout(this.tmrResize);
// resize is called multiple times per second,
// this helps to seperate the call,
// and ensure a little time gap (1/4 second here)
this.tmrResize = setTimeout(windowResize, 250);
});
})
html, body { margin: 0; padding: 0; }
#image-gallery {
background: blue;
color: white;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
#page { background: white; color: red; height: 400px; position: relative; z-index: 1; }
p { padding: 3em; text-align: center; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="image-gallery">
<p>
image Gallery
</p>
</div>
<div id="page">
<p>
next page
</p>
</div>
Someone passed by and then voted -1 to my question. I'd just like to know who's the braveheart that judges others without even posting a simple comment. This behaviour should be forbidden, we're not on 9gag neither 4chan.

Changing the background image according to resolution - javascript only

there's a lot of this question scattered over stackoverflow, but I can't seem to find an answer that specifically suits my situation.
I have made a background in HD 1920x1080 for a school project I'm making, and I'm trying to make it fit for every resolution there is. So what I did was resizing this image for every specific resolution, putting me in an awkward spot to code it, as I cannot use jQuery, I'm not allowed to.
I'm thinking of using the screen.width property, but I'd need a length too as I have multiple backgrounds with the ...x768 resoulution.
Is there anyone who'd be able to tell me how to change my body's background, depending on the user's height and width of the screen?
Thank you very much,
Michiel
You can use window.innerWidth and window.innerHeight to get the current dimensions of your browser's window.
Which means that if your browser takes half of your 1920x1080 desktop, it'll compute to something like:
window.innerWidth ~= 540
window.innerHeight ~= 1920 // actually something smaller because it doesn't count your browser's chrome
Your window can of course change size, and if you want to handle that, you can listen to the event "resize" for your window:
window.addEventListener('resize', function () {
// change background
});
To change the body's background without jQuery, you can do something like this:
document.body.style.backgroundImage = "url(/* url to your image...*/)";
To recap:
// when the window changes size
window.addEventListener('resize', function () {
var windowWidth = window.innerWidth; // get the new window width
var windowHeight = window.innerHeight; // get the new window height
// use windowWidth and windowHeight here to decide what image to put as a background image
var backgroundImageUrl = ...;
// set the new background image
document.body.style.backgroundImage = "url(" + backgroundImageUrl + ")";
});
I am not sure what browsers you are supposed to be compatible with. This should work in all latest versions of the big browsers.
You may check the window width and change the background depending on the results.
var width = window.innerWidth;
var height = window.innerHeight;
var body = document.body;
if (width <= 1600 && height <= 1000) {
body.style.background = "url(path/to/1600x1000.jpg)";
}
if (width <= 1400 && height <= 900) {
body.style.background = "url(path/to/1400x900.jpg)";
}
// continue as desired
http://jsbin.com/wosaduho/1/
Even better, use some media queries to reduce javascript required.
#media screen and (max-width: 1600px) {
.element {
background: url(path/to/1600x1000.jpg);
}
}
#media screen and (max-width: 1400px) {
.element {
background: url(path/to/1400x900.jpg);
}
}
body {
background-image: url(images/background.jpg);
background-size:cover;/*If you put "contain" it will preserve its intrinsic aspect ratio*/ background-repeat: no-repeat;
}
Try this
You might want to trigger a function like the following on window load and/or on window resize:
function SwapImage(){
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0),
el = document.getElementById('change-my-background');
// use conditionals to decide which image to show
if(w < 1200 && h < 800){
el.style.backgroundImage = "url('img_1200x800.png')";
}
if(w < 900 && h < 600){
el.style.backgroundImage = "url('img_900x600.png')";
}
// etc...
}

Browser detection using javascript failing on refresh

I'm trying to detect for devices that do not have support for position:fixed. EDIT: I've fixed the code so it's detecting features rather than browser/OS detection.
I think I was confusing people when I first typed this out. My issue is coming into play when I refresh the page. The height is being incorrectly calculated, which is a completely different issue I know, but am looking for assistance nonetheless.
Updated detection script below:
function fixed() {
var container = document.body;
if (document.createElement && container && container.appendChild && container.removeChild) {
var el = document.createElement('div');
if (!el.getBoundingClientRect) return null;
el.innerHTML = 'x';
el.style.cssText = 'position:fixed;top:100px;';
container.appendChild(el);
var originalHeight = container.style.height,
originalScrollTop = container.scrollTop;
container.style.height = '3000px';
container.scrollTop = 500;
var elementTop = el.getBoundingClientRect().top;
container.style.height = originalHeight;
var isSupported = (elementTop === 100);
container.removeChild(el);
container.scrollTop = originalScrollTop;
return isSupported;
}
return null;
}
//TEST FOR MOBILE, SET TOP IMAGE TO RELATIVE
if(fixed()) {
image_height = jQuery("#outer_homepage_image").height() - 45;
jQuery("#content").css("top",image_height);
jQuery(window).resize(function() {
image_height = jQuery("#outer_homepage_image").height() - 45;
alert(image_height);
jQuery("#content").css("top",image_height);
});
} else {
jQuery("#outer_homepage_image").css("position","relative");
}
This is an extremely brittle and ill-conceived thing to be doing.
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
For example, iOS has fully supported position:fixed properly since iOS 4. We're now on 6. For Android & Blackberry, I'm not sure but would err on the side of "supported".
You need to test for features, not user agent. As I said, you could have one iOS device that doesn't support it and another one that does. Indeed, most do these days.
Here's a helpful link to lead you to moral, godly choices: http://kangax.github.com/cft/#IS_POSITION_FIXED_SUPPORTED
Thanks for all the support guys. I solved it with jQuery(window).load(function() {
it works now because everything else is loaded so I can calculate the proper height.

What is different with window and div widths between firefox and IE

I have a web page that uses a scrolling div to display table information. When the window is resized (and also on page load), the display is centered and the div's scrollbar positioned to the right of the page by setting its width. For some reason, the behaviour is different under firefox than IE. IE positions/sizes the div as expected, but firefox seems to make it too wide, such that the scrollbar begins to disappear when the window client width reaches about 800px. I'm using the following methods to set the position and size:
function getWindowWidth() {
var windowWidth = 0;
if (typeof(window.innerWidth) == 'number') {
windowWidth=window.innerWidth;
}
else {
if (document.documentElement && document.documentElement.clientWidth) {
windowWidth=document.documentElement.clientWidth ;
}
else {
if (document.body && document.body.clientWidth) {
windowWidth=document.body.clientWidth;
}
}
}
return windowWidth;
}
function findLPos(obj) {
var curleft = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
}
}
return curleft;
}
var bdydiv;
var coldiv;
document.body.style.overflow="hidden";
window.onload=resizeDivs;
window.onresize=resizeDivs;
function resizeDivs(){
bdydiv=document.getElementById('bdydiv');
coldiv=document.getElementById('coldiv');
var winWdth=getWindowWidth();
var rghtMarg = 0;
var colHdrTbl=document.getElementById('colHdrTbl');
rghtMarg = parseInt((winWdth - 766) / 2) - 8;
rghtMarg = (rghtMarg > 0 ? rghtMarg : 0);
coldiv.style.paddingLeft = rghtMarg + "px";
bdydiv.style.paddingLeft = rghtMarg + "px";
var bdydivLft=findLPos(bdydiv);
if ((winWdth - bdydivLft) >= 1){
bdydiv.style.width = winWdth - bdydivLft;
coldiv.style.width = bdydiv.style.width;
}
syncScroll();
}
function syncScroll(){
if(coldiv.scrollLeft>=0){
coldiv.scrollLeft=bdydiv.scrollLeft;
}
}
Note that I've cut out other code which sets height, and other non-relevant parts. The full page can be seen here. If you go to the link in both IE and firefox, resize width until "800" is displayed in the green box top-right, and resize height until the scrollbar at the right is enabled, you can see the problem. If you then resize the IE width, the scrollbar stays, but if you resize the firefox width wider, the scrollbar begins to disappear. I'm at a loss as to why this is happening....
Note that AFAIK, getWindowWidth() should be cross-browser-compatible, but I'm not so sure about findLPos().... perhaps there's an extra object in Firefox's DOM or something, which is changing the result??
You are dealing with "one of the best-known software bugs in a popular implementation of Cascading Style Sheets (CSS)" according to Wikipedia. I recommend the Element dimensions and CSS Object Model View pages on Quirksmode.org.
Also: I think you'll find that Safari and Opera behave like Firefox in most circumstances. A more compatible approach to working around these problems is testing for, and making exceptions for, MSIE instead of the other way around.
Ok, I found the problem. Seems to be that firefox does not include the style.paddingLeft value in its style.width setting, whereas IE does, thus the div was ending up exactly style.paddingLeft too wide. That is, if for example style.paddingLeft is 8, IE's style.width value would be 8 more than FireFox's - and thus the inverse when setting the value, for FireFox I needed to subtract the style.paddingLeft value
Modified code with:
if (__isFireFox){
bdydiv.style.width = winWdth - bdydivLft - rghtMarg;
} else {
bdydiv.style.width = winWdth - bdydivLft;
}
As long as you don't include a valid doctype, you can't expect consistent results, due to Quirks Mode. Go add one (HTML 4.01 Transitional is fine), then let us know if it still occurs.
Also see http://en.wikipedia.org/wiki/Quirks_mode.
In your getWindowWidth() function, whenever you grab the width of something, instead of this:
windowWidth = document.documentElement.clientWidth;
try this
windowWidth = Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth);
A detail to help optimize some of your code:
function getPos(elm) {//jumper
for(var zx=zy=0;elm!=null;zx+=elm.offsetLeft,zy+=elm.offsetTop,elm=elm.offsetParent);
return {x:zx,y:zy}
}
(jumper is a user who posted this code in Eksperten.dk)

Categories

Resources