Changing grid depending on device orientation - javascript

I'm trying to change the size of divs depending of screen size.
If the phone is laying it changes the sizes of divs.
Example:
block is default: 330px width and 250px high on a 768x1280 screen resolution.
The factor is:
width: 330px; factor x 2,18
height: 250px; factor x 5,12
When i change my phone to laying the sizes should be:
width: 587px
height: 150px
which doesnt work in the first place, can someone tell my why not?
js:
var devicewidth = $( window ).width();
var deviceheight = $( window ).height();
var mbwsize = devicewidth / 2.18;
var mbhsize = deviceheight / 5.12;
var mbisize = mbhsize / 1.25;
$('#mainmenublok').css('width', mbwsize+'px');
$('#mainmenublok').css('height', mbhsize+'px');
$('#mainmenublok').css('background-size', mbisize+'px'+mbisize+'px');
dont get errors, it just keeps the content in the middle as 720px width (768 - offset)
I changed the main div already here:
$('#maintable').css('width', devicewidth+'px');
Will try to change window to document but can someone look at this?
With document it doesnt change either.
The calculation is correct if you look at the picture at the debug.
I also tried it in a function but that did not work.
Added a picture to explain what happens
explain:
debug:

Based on the HTML provided by the author in the comments
<div onclick="bb.pushScreen('timeline.html', 'timeline');"class="mainmenublok" id="blocktimeline" style="background-image:url(ico/timeline.png); background-size:200px 200px; background-repeat: no-repeat; background-position:center;">
<img id="pictimeline" src="ico/bbaction.png" width="50" height="50" style="display:none;">
</div>
and the js used as shown above, I suggest to use $('.mainmenublok').css('width', mbwsize+'px'); instead of $('#mainmenublok').css('width', mbwsize+'px');. Dots are used to indicate classes in CSS, as hashtags are used to indicate ID's.

You could use mediaqueries or device.js?

The way you are trying to achieve by script.... Is okay but in some browser it may give you bugs ... better you try with any of the css frameworks like twitter bootstrap its not really huge.... the your site will be responsive as according to your device....

Related

Can I determine the actual width/height of an element on a web page?

To illustrate my question, here is a not-real example:
<img src='myimage-low.png' style='width: 150px;'>
<img src='myimage-high.png' style='width: 150px;'>
myimage-low.png is 150px x 100px
myimage-high.png is 1500px x 1000px
When I am zoomed all the way out on the web page, both images look the same. When I zoom in, the high definition image looks much better.
If I use javascript to get the image width with $(elem).width();, it says (as I would expect) 150px for both, regardless of the zoom.
Is there a way in javascript to get the actual screen size of the element as presented to the user? In my above example, they might both say "100px" when I'm fully zoomed out, and "1000px" when I'm fully zoomed in.
Note - I need to be able to need this for both <img> elements as well as any element that might have a css background-image.
For context, this is to determine which resolution of an image to load. There's no point in loading the 1500px if the user is on a low resolution and it will just be resized in the browser to 300px - they might as well have the 500px version which is faster to download.
Say hello to window.devicePixelRatio:
var el = document.querySelector('img');
function getElemSize(el) {
var rect = el.getBoundingClientRect();
return {
width: Math.round(rect.width * window.devicePixelRatio),
height: Math.round(rect.height * window.devicePixelRatio)
};
}
function updateSize() {
var size = getElemSize(el);
document.querySelector('p').innerHTML = JSON.stringify(size);
}
el.addEventListener('load', updateSize);
addEventListener('resize', updateSize);
<img src="https://howitworks.wpengine.com/wp-content/uploads/2015/09/214887-puppies-cute-puppy.jpg" style="width: 150px">
<p></p>
You can use the visualViewport API to multiply the width by the scale if you're looking for pinch zoom:
const { scale } = window.visualViewport;
const width = $(elem).width() * scale;
I tried adding a snippet for an example, but according to the spec the window.visualViewport.scale inside of an iframe is always 1. As long as your content is not in an iframe, this method will work for giving you the scale of the pinch zoom (tested in my browser console)

How can I control an image's size

I am a skilled database / application programmer for the PC. I am also an ignorant html / javascript / web programmer.
I am creating some documentation about some .Net assemblies for our intranet. Ideally I would like to display an image full size if the browser window can fit it. If not then I would like to reduce it and toggle between a small version and full size version by a click. It is a dependency chart and can be different sizes for different pages. I would prefer a single function to handle this but being it is for our use none of the requirements I mentioned is set in stone. I would like to make it work well but nothing is mandatory.
I read a lot of stuff but couldn't find anything that matched what I wanted. First I tried this (after a few iterations):
<img src='Dependancy Charts/RotairAORFQ.png' width='100%' onclick='this.src="Dependancy Charts/RotairAORFQ.png";this.width=this.naturalWidth;this.height=this.naturalHeight;' ondblclick='this.src="Dependancy Charts/RotairAORFQ.png";this.width="100%";'>
It has problems. First off it enlarges a small image and it looks funny. Second I would have to put the code in every page. Third it requires a double click to restore it. I was going to live with those short commings but the double click fails. I can't figure out how to restore it.
So I tried to get fancy. I couldn't figure out how to get past problem 1, but solved 2 and 3 by creating a function in a separate file. Then I ran into what appeared to be the same problem. This was my second attempt:
function ImageToggle(Image)
{
if (ImageToggle.FullSize == 'undefined')
ImageToggle.FullSize = false;
if (ImageToggle.FullSize)
{
Image.width='100%';
ImageToggle.FullSize = false;
}
else
{
Image.width=Image.naturalWidth;
ImageToggle.FullSize = true;
}
return 0
}
And in my page:
<img src='Dependancy Charts/RotairAORFQ.png' width='100%' onclick='ImageToggle(this)'>
Can what I want be done? It doesn't sound impossible. If it is a large amount of effort would be required then alternate suggestions are acceptable.
You're probably interested in the max-width: 100% CSS property, rather than a flat-out width:100%. If you have a tiny image, it'll stay tiny. If you have a huge image, it gets resized to the width of the containing element.
For example: http://jsbin.com/kabepo/1/edit uses a small and a huge image, both with max-width:100%. As you can see, the small image is untouched, the huge image is resized to something sensible.
I would recommend that you set a the max-width: 100% CSS property for the image.
This will prevent the image's width from expanding to be greater than the container's width.
You can also do the same with max-height: 100% if you are having problems with the image overflowing vertically.
Please see this JSFiddle for an example.
(Note: If you set both a width and a height attribute on the <img> tag directly or in your CSS file your image will not be scaled proportionally.)
Does it have to be a toggle or would a mouseover work for you as well?
<style>
.FullSize { width:100px; height:auto; }
.FullSize:hover { width:90%; height:auto; }
</style>
<img src="Dependancy Charts/RotairAORFQ.png" class="FullSize">
Note: when image is made larger IN the page - the surrounding content will be displaced around it - depending on how you have set up the layout.
Also if you have any body margins or table or div paddings, using image width at 100% will make the page scroll. To check just change 90% to 100% and work your way up / down.
You could also force the image to be a specific size until the browser gets made smaller by the user / has a smaller resolution.
<style>
.FullSize {width:1000px;max-width:100%;height:auto;}
</style>
<img src="Dependancy Charts/RotairAORFQ.png" class="FullSize">
A tip: the image used must be the largest one. So minimum width of lets say 1200 pixels wide (if that is the forced image size you use). That way regardless of size it is it will remain clearer than a small image becoming a large. Since it's an intranet, file size shouldn't be an issue.
Thanks all for your help. Rob and Mike both pointed me to an excellent solution. I now have my page load with an image that fits the browser window, resizes with the browser and if the user is interested they can expand the image and scrollbars appear if necessary. I got this to work in a function so minimal code is needed for each page.
To load the image:
<p style="overflow:auto;">
<img src='Dependancy Charts/RotairAORFQ.png' width="100%" onclick='ImageToggle(this)'>
</p>
And the function:
function ImageToggle(Image)
{
if (ImageToggle.FullSize == 'undefined')
ImageToggle.FullSize = false;
if (ImageToggle.FullSize)
{
Image.style="max-width: 100%";
ImageToggle.FullSize = false;
}
else
{
Image.style="max-width: none";
Image.width=Image.naturalWidth;
ImageToggle.FullSize = true;
}
return 1
}
if you want to get current browser window size and if you want to do it on a click event so try this in jquery or javascript:
<script>
$("#myButton").click(function(){
var x = window.innerHeight; // put current window size in x (ie. 400)
});
</script>

JS scrollbar with fluid height

I'd like to personalize the scrollbar of a div whith a fluid height :
section {
max-height:70%;
overflow-y:auto;
}
I have found two smart light snippets : a Jquery plugin (http://baijs.nl/tinyscrollbar/) and a pure JS one (http://gondo.webdesigners.sk/javascript-scrollbar/). The problem is that these snippets do not accept % value for the height. For example, with tinyscrollbar, i have to put this :
section .viewport {
width: auto;
height:440px;
overflow: hidden;
position: relative;
}
If I put "height:100%;" or "height:auto;", the content disappears ! Why does it accept px and not % ? I'd like to understand it...
Which part of the JS/JQuery code should I change/add in order to insert the fluid height of the section ?
It's hard to follow without more example code (get in the habit of posting more code please), but I think something like this is what you're after.
--- Why don't you track the height of the context (outer div?) and the height of the inner div (section) and calculate them as they change?
var context_height = $("#context_div").height();
var section_height = $("section#id").height();
var percentage = section_height / context_height;
var measurement = percentage + "%";
$(section_height).css("height", measurement); // trigger this with a callback if heights need updating - possibly even re-initializing any scroll plugins, if necessary.

Robust way to display an image with one fixed dimension

Lets say that we have an image uploaded by the user, the upload script limits the mb but not the image size (so could be any proportion, 600X200,200X350, and so...).
Im already showing this image in one part on my site using the twitter bootstrap image handler written on css, thats good for a profile picture, the problem is that now I want that image to be a cover (like facebook/twitter cover image), my site is responsive so the width of the cover is 900px or 100% if the screen resolution is less than 900px wide. The height is always fixed to 200px. So I know there is a way to control the correct image display using CSS (maybe with jquery too) but Im not a front-end dev, Im a php dev and I dont want to use server side scripts for doing this. So im looking for suggestions or pieces of codes (css, javascript) to start with, I belive that it have to be an already made solution for this, but I dont find any on google. Thanks for any advice!
I would definitely not advise to use a css-only solution. Not even a client-side solution if the uploaded pictures can have any resolution. You want to use a php script to save resized versions of the uploaded images and serve those to the client. Either as a block's background-image and use css (not cross browser) or as an img tag and use js to resize.
css:
.myselector{
background-size: cover;
}
or js (jquery):
$(function(){
var containers = $('.myselector'), w = $(window);
function onResize(){
//resize code
containers.each(function(){
var $this = $(this),
w = $this.width(),
h = $this.height(),
ratio = w/h,
$img = $('img',$this); // assuming there is only one img in each container
$img.css({'width':'auto','height':'auto'});
var iw = $img.width(), ih = $img.height(), iratio = iw/ih;
if(iratio>ratio){
$img.css({
height:'100%',
width:'auto',
marginLeft: (w-iw*(h/ih))/2
});
}
else{
$img.css({
width:'100%',
height:'auto',,
marginTop: (h-ih*(w/iw))/2
});
}
});
}
w.bind('resize',onResize);
//resize on each image load event
$('img',containers).bind('load',onResize);
onResize();
});
Here is a working fiddle : http://jsfiddle.net/kHxd2/2/
The image's onload listener might need tweeking to react when cached images are rendered in IE: http://css-tricks.com/snippets/jquery/fixing-load-in-ie-for-cached-images/
Also you might want to set css rules for rare non-js browsers... (.myselector img{width:100%;})
EDIT : container css:
.myselector{
width: 100%;
max-width: 900px;
height: 200px;
margin: auto; /* centering */
overflow: hidden;
}
see updated fiddle: http://jsfiddle.net/kHxd2/3/
The best solution is to embed the image containers in a main wrapper div and apply the above css rules to that big container.
Here is some useful code to take care of server-side resizing : http://www.9lessons.info/2009/03/upload-and-resize-image-with-php.html
You have to put this image as background-image, and then use style:
background-image: url(url/to/your/image.png);
background-size: cover;
There is a property in css3 called as background-size:cover; and background-size:contain;. You might want to use them to suit your needs.
contain
Specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.
cover
Specifies that the background image should be scaled to be as small as possible while ensuring both its dimensions are greater than or equal to the corresponding dimensions of the background positioning area.

jquery - stretch background image to fill document rather than window?

I'm using this plugin: https://github.com/srobbin/jquery-backstretch to stretch a background in a good way.
So the issue is that if the content of the document is long enough to cause a scrollbar, then when you scroll, the image stays in the same place (just looks like a stationary background). You can see it in his demo here: http://srobbin.com/jquery-plugins/jquery-backstretch/ (this page uses the plugin. Just scroll and notice the background doesn't move).
I'm wondering if there's a way to change the plugin to not use the window height or something and rather use the document height? I've looked, but to no avail. I know this isn't a great idea in the case that the content is long, but it's done on only a single page that doesn't have much content at all. Really the only issues are if the browser real estate (not counting the chrome) is like less than around 650px in height.
Here's the plugin code. Pretty short and well written from what I can tell:
https://github.com/srobbin/jquery-backstretch/raw/master/jquery.backstretch.js
I once had the same problem, this was my solution.
$(window).resize(bg);
function bg() {
var imgWidth = 1088,
imgHeight = 858,
imgRatio = imgWidth / imgHeight,
bgWidth = $(document).width(),
bgHeight = bgWidth / imgRatio;
$('body').css({backgroundPosition: 'top center'});
if ($(document).width() < imgWidth && $(document).height() < imgHeight && $(document).height() > bgHeight) {
$('body').css({backgroundSize: 'auto 100%'});
} else {
$('body').css({backgroundSize: '100% auto'});
}
}
bg();
$('body').css({backgroundRepeat: 'repeat-x'});
$('body').css({backgroundImage: 'url("images/bg-state/bg_static2.png")'});
Note: It do not stretch on IE due to the code uses the css3 property background-size and you need to set your own width and height of the image in the code.
Another approach with scrollable content and a fixed background would be to just use an <iframe> or fixing the <img> on a layer. Then you wouldn't need to depend on jQuery (which I think is a bit heavy) for something that could be done on the browser without it.
<body background="background.png">
<iframe src="content.html" height="600"/>
</body>
Also found another way to do it with layers:
<img src="background.png" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index:-1;" />
<div style="position: static;z-index: 1; ">
content
</div>
Without paying respect to the image ratio, I believe you could set bgHeight to $("body").height().

Categories

Resources