Use javascript to change background css on browser resize - javascript

So, I want the background-size to change when the browser height is equal to 2/3 of the browser width. Here is the code I've tried, and I can't get it to work.
<body id="body" onresize="BG_resize()">
<script>
function BG_resize() {
var w = window.innerWidth;
var h = window.innerHeight;
if ((w * (2 / 3)) < h){
document.getElementById("body").style.background-size = "auto 100%";
}
}
</script>
</body>
The css:
#body {
background:url("Layout/BG.jpg");
background-size:100% auto;
}

Your JS should use backgroundSize, not background-size:
document.getElementById("body").style.backgroundSize = "auto 100%";

Another alternative to all of these is to use media queries (since you're doing this on the window) and get rid of the javascript all together. This will run smoother as the browser does most of the work for you.
Looks like the query you are looking for is the aspect-ratio so something like:
#media screen and (min-aspect-ratio: 2/3)
{
body {
background-size: auto 100%;
}
}
#media screen and (max-aspect-ratio: 2/3)
{
body {
background-size: 100% auto;
}
}

Another alternative which I find easier is using jQuery. You can simply use the resize() event handler. Below is an example:
$(window).on('resize', function () {
//Here you can add your code that you want to execute on resize
})
To then change the css you can also use jQuery .css().

http://fofwebdesign.co.uk/template/_...tio-resize.htm
.target-ratio-resize {
max-width: 960px; /* actual img width */
max-height: 150px; /* actual img height */
*height: 150px; /* actual img height - IE7 */
background-image: url(students.jpg);
background-size: cover;
background-position: center;
}
.target-ratio-resize:after {
content: " ";
display: block;
width: 100%;
padding-top: 66.666%; /* 2:3 ratio */
}

Related

Creating responsive 'Image Map' for elements to match elements of background image (JS/CSS) (React) [duplicate]

I'm trying to create a map of button elements that overlay a full-screen image, positioned over all the 'buttons' depicted on the image. When the image resizes, the button elements should resize as well.
I initially used an SVG image map for this, but it had a positioning bug (the link below) that didn't allow for the video player inside the foreignObject to show.
SVG foreignObject and absolute positioning
I figured using absolute positioning, and JS to measure the width of the background image was the best way to go. However, I'm having trouble making it work.
Below is the project, with the white box needing to be positioned over the background image (the entire box, with chocolates, and the screen).
The image is within a div as a background, like so:
export const BackgroundLightsOn = styled.div`
position: absolute;
background: url(${BgLightsOn});
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
height: 100%;
width: 100%;
border: 1px solid red;
`
Unfortunately, getting the dimensions of this DOM element gets the dimensions of the div, not the image (which is sometimes larger than the viewport). Below is the 'resizing' code, but this connects to backgroundRef (which is the div element the image is the background, not the image itself).
import React, { useEffect, useRef } from 'react';
import {
TruffleTinContainer,
TruffleTinOutside,
} from '../truffle-tin/styledTruffleTin';
export default function TruffleTin({ backgroundRef }) {
const truffleTinRef = useRef();
const initialPos = { x: 150, y: 150 };
const padding = 25;
let truffleBoxWidth = 0;
let truffleBoxHeight = 0;
useEffect(() => {
truffleBoxWidth = truffleTinRef.current.offsetWidth;
truffleBoxHeight = truffleTinRef.current.offsetHeight;
resize();
}, []);
function resize() {
let backgroundDivRect = backgroundRef.current.getBoundingClientRect();
truffleTinRef.current.style.left =
(initialPos.x / truffleBoxWidth) * backgroundDivRect.width -
padding +
'px';
truffleTinRef.current.style.top =
(initialPos.y / truffleBoxHeight) * backgroundDivRect.height -
padding +
'px';
}
useEffect(() => {
window.addEventListener('resize', resize);
return () => window.removeEventListener('resize', resize);
});
return (
<TruffleTinContainer ref={truffleTinRef}>
I'm the truffle tin
</TruffleTinContainer>
);
}
See the GIF below for the issue:
What's the best way to get this div to proportionally match the width of the background image?
(Edit: I changed the 'div with image background' to an img tag, but even then, the getBoundingClientRect shows not the width of the image, but the width of the viewport:
(in other words, even though the image is much wider than the viewport, I'm still getting the viewports dimensions, when what I want is the image's dimensions))
You don't need JS for that. This is achieved with plain CSS, all you need is the button center positions relative to left-top corner of the block. Sample HTML/CSS:
<div class='wrapper'> <!-- Will need this later -->
<div class='container'>
<a class='button' style='--left: 25%; --top: 20%'>1</a>
<a class='button' style='--left: 35%; --top: 80%'>2</a>
</div>
</div>
.container{
position: relative;
background: url('/path/to/image');
background-size: 100% auto;
}
.button{
position: absolute;
left: var(--left);
top: var(--top);
transform: translate(-50%, -50%); /* Move button a bit so its center matches the actual position */
/* These are just for visualization */
width: 50px;
height: 50px;
border-radius: 100%;
background: pink;
display: flex; align-items: center; justify-content: center;
}
The next step is to make .container have a constant width, or at least a constant width/height ratio if you care about vertical resizing. The constant width is achieved with a simple min-width. To avoid horizontal scroll we will add a .wrapper to hide the cut-off sides:
.wrapper{
display: flex;
align-items: center;
max-width: 100%;
overflow: hidden;
}
/* A-and a min-width for .container */
.container{
min-width: 1200px; /* Or whatever */
}
If you need a fixed ratio:
.container::before{
content: '';
display: block;
padding-top: 56.25%; /* 56.25% of the parent width this is, ratio 16x9 */
}
min-width can still be applied if needed. There's an aspect-ratio CSS property that can be used instead of that pseudo-element hack, but it is supported only in relatively fresh browser versions; still might be used if you don't plan supporting a little outdated browsers.

make the browser window as same as the element's size while resizing browser window. or atleast maintain same aspect ratio of browser as element have

while resizing my browser window i can resize the element div in it. But unwanted spaces/scope on left, right, top and bottom are appearing. I want the browser window's size as same as the div have. Or atleast find the aspect ratio of a div and accordingly we maintain same aspect ratio of the browser window. Ex: if div aspect ratio is 16:9, then we make the browser aspect ratio also same so that we can remove the unwanted space/scope in the browser window.
This is a sample script, instead of using div im using canvas. Help me with this.
<style>
*{padding:0; margin:0}
html,body {
width: 100%;
margin: 0;
padding: 0;
}
#main {
margin: 0 auto;
width: 963px;
height: 642px;
}
#preload {
display: block;
position: absolute;
width: 100%;
height: 100%;
margin:auto
}
.loading {
position:absolute;
top: 43%;
left: 47%;
z-index: 2;
display: none;
}
section{
position:absolute;
top:0
}
a1, a2, a3, a4, a5{display:block}
</style>
<div id="main">
<img id="preload" src="preload.jpg"/>
<img class="loading" src="image.jpg" />
<section>
<a1></a1>
<a2></a2>
<a3></a3>
</section>
</div>
<script src="jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function() {
$(window).on('resize', function(){
var maxWidth = $(window).width();
var maxHeight = $(window).height();
var ratio = $("#main").height() / $("#main").width();
if(maxWidth * ratio > maxHeight) {
$("#main").height(maxHeight);
$("#main").width(maxHeight / ratio);
} else {
$("#main").width(maxWidth);
$("#main").height(maxWidth * ratio);
}
$("#preload").width($("#main").width());
$("#preload").height($("#main").height());
$("a1").text(maxWidth);
$("a2").text(maxHeight);
$("a3").text(ratio);
}).trigger('resize');
})(jQuery);
I'm not 100% sure what you are looking for but you can set any element to fill the browser like so...
.element{
width:100%;
height: 100vh;
}

How to vertically center jQuery Modal?

jQuery code:
function thumb(id,ths) {
if (<?=$loggedin?>) {
$.post(base_url+"index.php/myad/addthumbs", {uniqueid:id});
$(ths).addClass("red");
} else {
_ths=$(ths);
var number = Math.floor(Math.random()*90000) + 10000;
$("#captcha").attr("data-id",id);
$("#captcha").text(number);
$("#pop").modal("show");
}
}
How can I center modal? Please help me and thanks in advance.
I find solution on google and on stackoverflow but question is asked for bootstrap based modal when it build by a pure jquery.
Give your popup a fixed css like this:
#pop {
position:fixed;
top:50%;
left:50%;
}
Then align it by it´s width and height in your JS:
$("#pop").css({
"margin-top":-($(this).height()/2),
"margin-left":-($(this).width()/2)
});
One method is you can adjust the percentage of margin-top style
.modal-dialog {
margin-top:10%; /* Based on your modal height adjust the percentage */
}
OR
.modal-dialog {
padding-top:10%; /* Based on your modal height adjust the percentage */
}
Without using jQuery, you can simply use display: table to the main content container together with margin: auto.
A working example of this centered modal is here.
Basically, these are the important rules:
.modal-content {
display: table;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
max-width: 60%; /* here you can also use a fixed width */
overflow: auto;
z-index: 50;
}
Use JavaScript or jQuery to trigger the opening and closing of the modal.

How to keep div in center-height when I resize the browser window?

I am trying to center in height a div, however it does not work when I resize the browser screen.
How to edit this to achieve the adjustable margin-top on resize?
Thank you
<script>
var h = $(window).height();
var parentHeight = h;
var childHeight = $('#a-middle').height();
$('#a-middle').css('margin-top', (parentHeight - childHeight) /2);
</script>
Edit:
The answer should be in js since flexbox won't work on IE-9
you should stick to a CSS solution though, there are several way to achive this
.alignVertical {
position:relative;
display:inline-block;
top:50%;
transform:translateY(-50%);
}
jsfiddle: https://jsfiddle.net/jorjmt70/
or using flexbox
.parent {
display:flex;
height:100vh;
background-color:red;
justify-content:center;
align-items:center;
flex-direction:column;
}
jsfiddle: https://jsfiddle.net/mdh9h876/
if you want to use flex box use autoprefixer to get deeper browsersupport:
https://github.com/postcss/autoprefixer
Although you can easily do this with pure CSS, your bounty stated that you want a JS answer.
If you are interested in a pure CSS answer, see this answer that has multiple different methods on how to center elements vertically/horizontally.
You could simplify your jQuery to the following:
$('#a-middle').css('margin-top', function () {
return ($(window).height() - $(this).height()) / 2
});
Then you could just place this within a resize event listener and chain the .resize() method in order to trigger the event initially when the browser loads.
Example Here
$(window).on('resize', function () {
$('#a-middle').css('margin-top', function () {
return ($(window).height() - $(this).height()) / 2
});
}).resize();
JavaScript equivalent (without jQuery):
Example Here
var verticalCentering = function () {
var el = document.querySelector('#a-middle');
el.style.marginTop = (window.innerHeight - el.offsetHeight) / 2 + 'px';
}
window.addEventListener('resize', verticalCentering);
verticalCentering();
For a div called 'center-me':
$(document).ready(centerDiv);
$(window).resize(centerDiv);
function centerDiv() {
var winHeight = $(document).innerHeight(),
divHeight = $('.center-me').height();
$('.center-me').css('marginTop', (winHeight - divHeight) / 2 );
}
You need to call it when the document is ready, to get it centered in the first place, then on resize-event, to keep it centered.
Here is the fiddle for it: Fiddle
A CSS solution could do the trick for you.
div.center {
height: 100px;
width: 300px;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -150px;
position: absolute;
background-color: red;
}
<div class="center">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
This CSS code work fine in IE8+, Firefox and Chrome.
But you must know the sizes of the DIV that you want to adjust correctly. If the height and width are dynamic, you just have to update the style accordingly with JavaScript. Don't forget to apply the class center in JS on need to your DIV.
Explanations :
margin-top : - height / 2 because top : 50% only centered vertically the top of the DIV.
margin-left : - width / 2 because left : 50% only centered horizontally the left of the DIV.
position : absolute so that the DIV can center over all the page.
This can be achieved using simple CSS with deep browser support back to IE8.
html, body {
height: 100%;
}
.parent {
display: table;
table-layout: fixed;
width: 100%;
height: 100%;
}
.child {
display: table-cell;
vertical-align: middle;
text-align: center;
background: red;
}
<div class="parent">
<div class="child">This is always centered.</div>
</div>
Using table-layout makes it simple: the child can be vertically aligned (top, middle, bottom) and will take up all the available height. You're not resorting to JavaScript, CSS with patchy support or having to hard-code any figures, it should just work.
Depending on the specifics of what you're looking to do, flexbox or - as a last resort - JavaScript might be required, but for most cases display: table-cell is your friend.
That said, if it's acceptable for older browsers to get a different layout, just use #Victor's answer: this is what flexbox is for.
To make a div always stay at the center of the screen, the properties you could use are top and left attributes after setting the position attribute to absolute. However you will need to set these properties dynamically when the browser is resized. This can be done using the JQuery method - resize().
/*css code*/
.div{
position:absolute;
top:100px;
left:50px;
background:black;
}
/*JS Code*/
function keep_div_centered()
{
window_height = $(window).height();
window_width = $(window).width();
obj_height = $('.keepincenter').height();
obj_width = $('.keepincenter').width();
$('.keepincenter').css('top',(window_height/2)-(obj_height/2)).css('left',(window_width/2)-(obj_width/2))
}
keep_div_centered();
$(window).resize(function(){
keep_div_centered();
})
/* HTML Code */
<div class="keepincenter"></div>
Link to the fiddle - http://jsfiddle.net/y0937t06/
$(window).resize(function () {
var h = $(document).height();
var parentHeight = h;
var childHeight = $('#imagegallery').height();
$('#imagegallery').css('margin-top', (parentHeight - childHeight) / 2);
});
For me, this is the holy grail of CSS :)
The most reliable method I found is setting the container element as follows:
display: -webkit-flex;
-webkit-justify-content: center; /* horizontal */
-webkit-align-items: center; /* vertical */
It is simple and has no prerequisites on any other CSS properties.
The fiddle below places content 30px above vertical center:
#container {
width: 500px;
height: 300px;
background-color: red;
display: -webkit-flex;
-webkit-justify-content: center;
-webkit-align-items: center;
}
#content {
background-color: green;
margin-bottom: 30px;
}
<div id="container">
<span id="content">Content</span>
</div>
Handle window_resize event of the current window and try putting above code there.
It should give you expectd functionality.
This approach is very useful when you want to center both vertically and horizontally an absolute position div. It work also on IE8
You need to set the both outer and inner divs as
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin:auto;
margin:auto it's fundamental to center divs in this case.
You could also set the height and width of the .in div and still you would see it centered vertically and centered also when you resize the browser.
* {
margin: 0;
padding: 0;
}
html, body {
position: relative;
height: 100%;
width: 100%;
}
.in, .out {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin:auto;
}
.in {
background-color: red;
height: 50%;
width:50%;
}
.out {
background-color: blue;
}
EXAMPLE 1 JSFIDDLE height, width: in percentages: http://jsfiddle.net/a_incarnati/1o5zzcgh/3/
EXAMPLE 2 - JSFIDDLE fixed height, fixed width
http://jsfiddle.net/a_incarnati/1o5zzcgh/4/
Give display: table-cell; to the parent and align the contents vertically using vertical-align and give the padding to adjust the necessary spacing from top.
.child{
display:table-cell;
vertical-align:top;
padding-top: 50px;
}
This will keep the margin uniform throughout.
use css
first give a height to your element.
#a-middle {
height: 20px;
position: fixed;
top: calc(50% - 10px);
left: 0;
}
or use js
$(function(){
$('#a-middle').each(function(){
var t = $(window).height()/2 - $(this).outerHeight()/2;
$(this).css({top: t + "px"});
});
});
$(window).resize(function(){
$('#a-middle').each(function(){
var t = $(window).height()/2 - $(this).outerHeight()/2;
$(this).css({top: t + "px"});
});
});
The problem with the previous solutions is that you won't be able to center the div, if he's larger than the available vertical size.
If you want your div to take 50% of the page you can use the CSS vertical height based unit:
.mydiv {
height: 50vh;
top: 50%;
left: 50%;
position: fixed;
width: 50vh;
margin-top: -25vh;
margin-left:-25vh;
border: solid black 1px;
}
So your DIV will not only be centered but also maintain its ratio.
Play with margin-left and margin-top of that div, using the width and height of the window and div.
$(function () {
makeDivCenter();
$(window).resize(function () {
makeDivCenter();
});
});
function makeDivCenter() {
var windowWidth = $(window).width();
var divWidth = $(".center").width();
var windowHeight = $(window).height();
var divHeight = $(".center").height();
$(".center").css({
'margin-left': (windowWidth / 2) - (divWidth / 2) + "px",
'margin-top': (windowHeight / 2) - (divHeight / 2) + "px"
});
}
Here is jsfiddle for your reference https://jsfiddle.net/fnuud7g6/

Div Square, width size based on 100% height

I'm trying to make a responsive square with the width size based on the (100%) height of the element. I believe it's impossible using only CSS.
The square width should be equal to the height (100% of the large container. The large container is more than 100% of the screen). The ratio has to be width=height to keep the square.
You could do this with a tiny inline image.
No JS, no extra files.
.container {
height: 150px;
width: 100%;
text-align: center;
background: #acd;
}
.square {
display: inline-block;
height: 100%;
background: #691;
}
<div class="container">
<div class="square">
<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" height="100%">
</div>
</div>
For a CSS-only solution (where you're sizing relative to the screen size), use viewport units. For example:
#media screen and (orientation:landscape) {
.box{
height: 100vh;
width: 100vh;
}
}
#media screen and (orientation:portrait) {
.box{
height: 100vw;
width: 100vw;
}
}
(You may want to reduce it to 98 units to eliminate scrolling)
Works great for divs that need to take up a precise proportion of screen space.
JSFiddle here.
Take a look... at the aspect-ratio property.
This property makes creating a square div based on height, in the easiest method possible. Here's some example code:
h2 {
font-family: calibri;
}
#parent {
height: 96px;
width: 256px;
background: grey;
margin-bottom: 16px;
}
#child {
height: 80px;
aspect-ratio: 1 / 1;
background: lightgrey;
}
#anotherParent {
height: 96px;
width: 256px;
background: grey;
}
#anotherChild {
height: 50%;
aspect-ratio: 1 / 1;
background: lightgrey;
}
<h2>Absolute height (80px/96px)</h2>
<div id="parent">
<div id="child">
</div>
</div>
<h2>Relative height (50%)</h2>
<div id="anotherParent">
<div id="anotherChild">
</div>
</div>
Here are a couple of links to help you understand the aspect-ratio property:
https://css-tricks.com/almanac/properties/a/aspect-ratio/
https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio
https://support.squarespace.com/hc/en-us/articles/115008538927
Since a square has same width and the height, and you know the width of the square, you can apply the same value to height.
If you can use JS, then please try this: (jQuery)
var wiDth = $('div').css('width'); // get width
$('div').css('height', wiDth); // apply that value to the height
Try it here: http://jsfiddle.net/afzaal_ahmad_zeeshan/vpGUK/
You can accomplish this using javascript. I'm assuming that you have a larger div container, in which you want a square, whose height is the same height as the container. The html is as follows:
<div id="container">
<div id="square" style="height:100%;">
</div>
</div>
In javascript, you would simply do:
<script>
var container = document.getElementById("container");
var square = document.getElementById("square");
square.style.width = container.style.height;
window.onresize=function(){
square.style.width = container.style.height;
};
<script>
Hope that helps
I think this can be a good 'css only' solution for you.
Cross browser working.
http://absolide.tumblr.com/post/7317210512/full-css-fluid-squares
Good to highlight this nice css rule:
If the vertical paddings (and margins) are specified in percent (%) values the size is a percent of the width of the containing element.
Put it on your <script src="http://code.jquery.com/jquery-1.10.2.js"></script> and try with jquery:
var totalHeight = 0;
$("#yourContainer").children().each(function(){
totalHeight += $(this).height;
});
$("#yourContainer").css('width', totalHeight + 'px');
Ok here the solution.
<div id="square" style="background-color:black;height:100%">test</div>
$(window).ready(updateWidth);
$(window).resize(updateWidth);
function updateWidth()
{
var square = $('#square');
var size = square.height();
square.css('width',size);
}
http://jsfiddle.net/j372H/7/
You can assign width and height to the container like this
.container {
width: 100vh;
height: 100vh;
}
It will create a square div with 100% height and width=height.

Categories

Resources