fullscreen & centred background image script - javascript

I have made a simple function that adapts the size of an image according to the size of the window. I can't determine when exactly, but sometimes the img does not fill the width of the screen, but continues to stick to the height. Any idea why this could be?
If i console log (iRatio <= wRatio) anything seems to fit, but the shown result is incorrect.
The img is set as postion: absolute; with: 100%; top:0; left:0; in the css.
$win contains $(window) and $img the background image
function autoImageSize($img, $win){
var wHeight = $win.height(),
wWidth = $win.width(),
iHeight = $img.height(),
iWidth = $img.width(),
iRatio = iWidth / iHeight,
wRatio = wWidth / wHeight;
if(iRatio <= wRatio){
$img.css({
width: "100%",
height: "auto",
top: "-" + ((iHeight - wHeight)/2) + "px",
left: 0
});
}else{
$img.css({
width: "auto",
height: "100%",
top: 0,
left: "-" + ((iWidth - wWidth)/2) + "px"
});
}
return [$img.width(), $img.height()];
};

the problem was:
left: "-" + ((iWidth - wWidth)/2) + "px"
and
top: "-" + ((iHeight - wHeight)/2) + "px"
this is a stupid way to do a negation, sometimes the result was --somenumber px. i fixed the problem by doing this operation only wen the iHeight is smaller then the wHeight oder the iWidth is smaller then wWidth and by calculating the negation with a multiplication by -1.

When you are setting the image's width to 100% it will fill up to its parent's width. As is the case with the height of 100%, but there the parent also needs a fixed height in pixels (as far as I know).
Instead of setting the height to 100% you should calculate the width matching the height of the window using the image's ratio:
var toWidth = $win.height() * iRatio;
$img.width(toWidth);

Related

How do I multiply with 0.8 in JavaScript

2020 edit: I was young and dumb and did not know how multiplication worked.
So, I need to embed a youtube video on a site, and I want it to take up 80% of the user's screen size. I found the following code to make it fullscreen. Can someone help me make it fullscreen -20%?
$(function(){
$('#video').css({ width: $(window).innerWidth() + 'px', height: $(window).innerHeight() + 'px' });
$(window).resize(function(){
$('#video').css({ width: $(window).innerWidth() + 'px', height: $(window).innerHeight() + 'px' });
});
});
Multiply the width and height of the window by 0.8 to get 80% of the width and height of the fullscreen.
$(function(){
$('#video').css({ width: $(window).innerWidth()*0.8 + 'px', height: $(window).innerHeight()*0.8 + 'px' });
$(window).resize(function(){
$('#video').css({ width: $(window).innerWidth()*0.8 + 'px', height: $(window).innerHeight()*0.8 + 'px' });
});
});
I think where you have width: $(window).innerWidth() + 'px'... you are saying let the width be the entirety of the page, the same with height.
Can you divide the $(window).innerWidth() by a certain size, such as 300?
That may change the size of the video for you.
Such as:
var smallerWidthWindow = window.innerHeight / 250; //(or required number)
then have width: smallerWidthWindow and height: smallerHeightWindow, using those variables to change your height and width.
$('#video').css({ width: smallerWidthWindow, height: smallerHeightWindow });

Image move with mouse position - box issue?

I had originally taken some information from here and expanded on it: onextrapixel.com/examples/interactive-background/index4.html
I have instead incorporated the image to move with mouse position on the page, however there seems to be an issue with there being a top "box" that cuts off some of the hovered image. You can see it in action on a sample page here
My css:
.top-image {
background:url('http://i.imgur.com/wZRaMrB.png');
position:absolute ;
top:400px;
width:100%;
z-index:0;
height:100%;
background-repeat: no-repeat;
}
My js:
$(document).ready(function() {
var movementStrength = 25;
var height = movementStrength / $(window).height();
var width = movementStrength / $(window).width();
$("body").mousemove(function(e){
var pageX = e.pageX - ($(window).width() / 2);
var pageY = e.pageY - ($(window).height() / 2);
var newvalueX = width * pageX * -1 - 25;
var newvalueY = height * pageY * -1 - 50;
$('.top-image').css("background-position", newvalueX+"px "+newvalueY+"px");
});
});
I also hope to repeat this for the right side of the page.
After some suggesting in the comments here is the jsfiddle https://jsfiddle.net/yx1w8ysr/#&togetherjs=D4Q1xTfcaO
If you know the image's size beforehand, you can set the size of your div fixedly and don't need to use background-size:contain. Instead set it to some relative value (less than 100%) so that you have a padding around for the movement of the background image. However if you don't know the size of the image, you should use background-size:contain to ensure that your image sits right inside your div container. However with this approach we cannot control the size of the image anymore. That means you cannot use background-position to move the image around (because the size fits its parent, moving will cause the image be cut off).
So you need some another wrapper/container and move your inner div (.top-image) instead of changing the background-position.
Here is the detailed code:
var movementStrength = 25;
var w = $(window).width();
var h = $(window).height();
$(window).mousemove(function(e) {
var pageX = (e.pageX - w / 2) / w / 2;
var pageY = (e.pageY - h / 2) / h / 2;
var newvalueX = pageX * movementStrength;
var newvalueY = pageY * movementStrength;
$('.top-image').css({
left: newvalueX + 'px',
top: newvalueY + 'px'
});
});
.container {
padding: 25px;
width: 35%;
height: 35%;
position: absolute;
top: 400px;
}
.top-image {
background: url('http://i.imgur.com/wZRaMrB.png');
position: absolute;
background-size: contain;
width: 100%;
z-index: 0;
height: 100%;
background-repeat: no-repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<div class="top-image"></div>
</div>

Fullscreen background video aspect ratio on resize

I have the following code to set a video as fullscreen background. It gets the browser dimensions and set the aspect ratio, so there should not be any black bars. Instead, either the top/bottom or sides overflow while still keeping the video centred.
The problem I have is if the the browser is resized. It kind of works, but I have a feeling that if the resize happens to fast, the script does not keep up, resulting in a white space along one of the edges.
Code below, jsfiddle here:
https://jsfiddle.net/RobertCS/r50ktjoh/2/
<div class="bgvideo">
<iframe src="https://player.vimeo.com/video/75542539?background=1&loop=1&title=0&byline=0&portrait=0&autoplay=1&badge=0" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen frameborder="0"></iframe>
</div>
body, html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.bgvideo {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden;
z-index: 1;
}
.bgvideo iframe {
position: absolute;
}
function videoIframe() {
//Get the browser dimensions and calculate aspect ratio
var browswerWidth = $(window).width();
var browswerHeight = $(window).height();
var aspectRatio = browswerHeight / browswerWidth;
if (aspectRatio < 0.5625) {
//Video too tall for viewport.
//Set the video width to the browser width
//Set height according to aspect ratio.
//Finally, offset top/bottom to keep video centred.
var newHeight = 0.5625 * browswerWidth;
$('.bgvideo iframe').css({
'width': browswerWidth + 'px'
});
$('.bgvideo iframe').css({
'height': newHeight + 'px'
});
$('.bgvideo iframe').css({
'bottom': -((newHeight - browswerHeight) / 2) + 'px'
});
} else {
//Video too wide for viewport.
//Set the video height to the browser height
//Set width according to aspect ratio.
//Finally, offset left/right to keep video centred.
var newWidth = browswerHeight / 0.5625;
$('.bgvideo iframe').css({
'width': newWidth + 'px'
});
$('.bgvideo iframe').css({
'height': browswerHeight + 'px'
});
$('.bgvideo iframe').css({
'left': -((newWidth - browswerWidth) / 2) + 'px'
});
};
};
$(window).resize(videoIframe);
$(document).ready(videoIframe);
just do it with a setTime function.
var resizeTimer;
$(window).on('resize', function(e) {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
videoIframe();
}, 250);
});

whay can't I change both image height and width at same time with javascript?

I have an image in a div and I want the image to stay centered at all times.
If the width of the image is wider than the screen, then I want the image to expand to the width of the view port. And if the image is shorter than the height of the view port then I want it to expand to the height of the view port.
In my code, when I expand the width, the height expands automatically, which is great since I don't have to calculate it. The height does the same thing. When the height is expanded, the width stays proportional.
However, if the width changes in such a way that the height is now smaller than then view port, then I need to check the height and bring it back up to the view port height (which should expand the width again but it doesn't). When I have to change both height and width at the same time, the automatic proportioning doesn't work. If I do one or the other, it does work.
How can I accomplish this so they can both be changed and work without distorting the image?
my code:
inner_width = $(window).innerWidth();
inner_height = $(window).innerHeight();
if (inner_width < original_pic_width ) {
$(pic).css({'width': original_pic_width});
}
else {
$(pic).css({'width' : inner_width });
}
if (inner_height < original_pic_height){
$(pic).css({'height': original_pic_height});
}
else {
$(pic).css({'height' : inner_height });
}
CSS contain is pretty nice.
$("div").css({
backgroundImage: "url(" + $("img").prop('src') + ")",
backgroundSize:"contain",
backgroundRepeat: "no-repeat"
});
div { width:200px; height:200px; border:1px solid red;}
div img { display:none }
<div>
<img src="http://www.somebodymarketing.com/wp-content/uploads/2013/05/Stock-Dock-House.jpg"/>
</div>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"
integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
crossorigin="anonymous"></script>
Here is a possible solution (not sure to understand clearly what you want though). Note that I'm not absolutely sure that the centering method is cross-browser.
var div = $("div");
var img = $("img");
var imgw = img.width();
var imgh = img.height();
var imgr = imgw / imgh;
var sizes = [300, 120];
var i = 0;
setInterval(function () {
div.width(sizes[i]);
i = (i + 1) % 2;
adjust();
}, 1000);
function adjust () {
var divw = div.width();
var divh = div.height();
var divr = divw / divh;
if (divr < imgr) {
img.width("100%");
img.height("auto");
} else {
img.width("auto");
img.height("100%");
}
}
div {
position: relative;
}
img {
display: block;
position: absolute;
top: 0; bottom: 0;
right: 0; left: 0;
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:120px;height:120px;border:10px solid #5900CC;">
<img style="width:100%;" src="http://i.stack.imgur.com/jKXi2.jpg" />
</div>
If you set both height and width... both dimensions, height and width will be set.
It should be enough to set just one dimension if you set the width=viewport's width if it's horizontal (width>height) or the height=viewport's height if it's vertical.
Find which dimension you have to change and change that one only. You can do that by checking the difference between the image's width and the window's innderWidth, and the difference between the image's height and the window's innerHeight. Whichever difference is greater is the one you need to change only. That should take care of the other dimension without having to resize both.

Optimizing how my jQuery code is written

I have just currently started learning jQuery and I seem to be able to get it work how I want but I feel that the way that I am writting it is not very efficient. Could anyone assist me in this example below:
$('.tiles-wrapper').css({top:'50%',left:'50%',margin:'-'+($('.tiles-wrapper').height() / 2)+'px 0 0 -'+($('.tiles-wrapper').width() / 2)+'px'});
$(window).resize(function() {
$('.tiles-wrapper').css({top:'50%',left:'50%',margin:'-'+($('.tiles-wrapper').height() / 2)+'px 0 0 -'+($('.tiles-wrapper').width() / 2)+'px'});
});
So here I am positioning a div in the center of the screen. And then it also does it again on window resize as its contents width properties are percentage values. It works perfectly but I can't help but feel that there must be a better way to write this. Any help would be greatly appreciated. Thank you
You can cache the object and trigger the resize event, this way the resize handler is executed on DOM Ready.
$(window).resize(function() {
var $elem = $('.tiles-wrapper');
$elem.css({
top: '50%',
left: '50%',
margin: '-' + ($elem.height() / 2) + 'px 0 0 -' + ($elem.width() / 2) + 'px'
});
}).resize()
var $tilesWrapper = $('.tiles-wrapper');
function setWrapperStyle () {
var halfWidth = $tilesWrapper.width() * 0.5;
var halfHeight = $tilesWrapper.height() * 0.5;
$tilesWrapper.css({
top: '50%',
left: '50%',
margin: '-' + halfHeight + 'px 0 0 -' + halfWidth + 'px'
});
}
setWrapperStyle();
$(window).on('resize', setWrapperStyle);
You should make a fonction with your first line :
function center(){
$('.tiles-wrapper').css({top:'50%',left:'50%',margin:'-'+($('.tiles-wrapper').height() / 2)+'px 0 0 -'+($('.tiles-wrapper').width() / 2)+'px'});
}
and then you call it a first time and you call it when you resize your window:
center();
$(window).resize(center);
Do you really need jquery here ?
You can use directly css
.tiles-wrapper{
top:50% ;
left:50% ;
width: //what u given
height: //what u given
margin-left: //tiles width/2
margin-right: //tiles height/2
position: //absolute or float
}
if you want to calculate height and width dynamically
just write this on document ready
var $elem = $('.tiles-wrapper');
$elem.css({
top: '50%',
left: '50%',
margin: '-' + ($elem.height() / 2) + 'px 0 0 -' + ($elem.width() / 2) + 'px'
});
In re-size it will automatically on center position.

Categories