Aspect Ratio Fill - the right way - javascript

I know, it has been asked before. The answers are insufficient although they are marked as correct.
I need something that fills a container with an image by showing the most of the image, centers it and preserves its ratio. Should be ajquery-plugin, a angular-directive or plain JS.
<div ratio-fill>
<img>
</div>
Of course should be enough where the script takes action then.
Solution for interest:
<div ratio-fill="http://img.url"></div>
CSS
*[ratio-fill] { background-size: cover;
background-position: center; }
Script (jQuery)
/* img-ratio-fill */
$(window).load(function(){
/* ratio-fill-directive */
$('*[ratio-fill]').each(function() {
var $this = $(this),
imgUrl = $this.attr( "ratio-fill" );
$this.css( "background-image", "url('" + imgUrl + "')" );
});
})

with css on the DIV
background-size: cover; background-position: center;

Related

Changing Image position when scrolling page

I'm new to javascript and wanna create a HTML page and would like to make an image like floating on my page and it will interacting when user scrolling up and down of the website but I just couldn't figure it out. Anyone has idea how to deal with it?
<script>
$(window).scroll(function () {
//You've scrolled this much:
// $('p').text("You've scrolled " + $(window).scrollTop() + " pixels");
var doc = doc
var x = document.getElementsByClassName("ImageTesting");
//x.style.top = "$(window).scrollTop()";
x.css({'top': $(window).scrollTop() +'px'});
console.log($(window).scrollTop() + "px")
//console.log(x.style.top)
});
</script>
You can achieve the same behavior using css's sticky property
.ImageTesting {
position: -webkit-sticky; /* safary */
position: sticky;
top: 0;
}
You can do it with simple CSS properties first mentioned above The CSS Sticky property with image tag or just
<div class="bgFloat"></div>
<style>
.bgFloat {
background-image: url(image.jpg);
background-attachment: fixed;
background-position: center;
background-size: contain;
background-repeat: no-repeat;
}
</style>
It will help you to fix the image position as background. Or if you want to continue with image tag then follow the 'position: sticky; top:0' or where ever you want to place your element.

changing html element background image js

i have searched google and on here but i cant exactly find a correct answer to my problem i used this code:
html {
background: url('../resources/imgs/bgs/mainbg.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
that i got from the internet to set a background image that is always in the center and fits perfecly in the browser and it works great but i ran into a problem. i need to change the background image on a button click but i dont know how to target the html tag is it even possible? many thanks :)
my question was flagged as a duplicate but my problrm is not just getting the style of the html elememnt but changing it the same as the code snippet using only pure javascript
You have to set both backgroundImage and backgroundSize property. Try the following:
document.querySelector('#btnSetImage').addEventListener('click', function(){
var html = document.querySelector('html');
html.style.backgroundImage = "url('https://www.noodleman.co.uk/images/source/google_merchant_bulk_category_assign/google.jpg')";
html.style.backgroundSize = 'cover';
});
<button type="button" id="btnSetImage">Set Background Image</button>
Simply use:
document.getElementsByTagName('html')[0].style.backgroundImage = "url('img_tree.png')";
With jquery you could do the following
$('html').on('click', function(){
$('html').css({
"background": "url('https://picsum.photos/1200/3300/?blur') no-repeat center center fixed",
"background-size": "cover"
});
});
You can access the html element directly with documentElement:
/*Just change the image source with javascript*/
document.querySelector('#changeImage').addEventListener('click', function() {
document.documentElement.style.backgroundImage = 'url("https://www.fillmurray.com/400/400")';
});
/*Base settings in CSS*/
html {
background: url('https://www.fillmurray.com/g/400/400') no-repeat center center fixed;
/*This Would be a greyscale image*/
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
<div style="color:#FFF;">Bill Murray!</div>
<!-- Just Some Content -->
<button id="changeImage">ChangeImage</button>

Force a background image to be loaded before other background images

Is there a way to force downloading a specific image (priority image) before other images are downloaded?
I use many background images. My landing page has a gradient fill used as my second image of my landing page.
landing page CSS:
.bg-img1::before {
background-image: url(https://mywebsite/images/myimage.jpg), linear-gradient(to top, #206020, white);
background-size: cover, cover;
}
I switched from using DOM ready detection as my background image gradient was displaying 3 or 4 seconds before my landing page image was downloaded...
$(function() {
// DOM ready, but image hasn't downloaded yet.
});
Now I use window.onload and everything is working fine, but I am adding more and more images and the downloading delay is becoming substantial.
window.onload = function() {
// delay, delay... finally my landing page with gradient displays
});
To reiterate my question, I would like to be able to make downloading my landing page a priority. Is there a way to ensure that my background image displays before my gradient is displayed if I switch back to using DOM ready?
add an image tag and place the source in it. make sure that you add display none to this tag. place this tag as high up in your body tag. this should prioritize your image loading. hope this works for you.
Maybe the script I did for you works as you expect. By using JS there's no possibility to set the CSS pseudo elements such the :before.
What I did, was to change the code so it provides the img URL as data attribute in the image containers.
Then using the JavaScript I hide all the image containers and start creating new images dynamically, and then I set the src attribute, to the value of the data-img of the section element.
Finally, I listen for the load and error event, and then I show again the container. This way you can be sure, that the image it is already loaded in the browser, and thus when the image container it is displayed will have the image already in place.
(
function ( $, window, undefined ) {
var img_container = null;
var img_loaded = 0;
var hide_img_containers = function hide_img_containers() {
if ( 0 < img_container.length ) {
img_container.hide();
}
}
var show_img_containers = function show_img_containers( $element ) {
$element.show();
}
var load_images = function () {
img_container.each(
function() {
var $section = $( this );
var $img = $section.attr( 'data-img' );
var img = document.createElement('img');
img.src = $img;
img.addEventListener(
'load',
function () {
show_img_containers ( $section );
}
);
img.addEventListener(
'error',
function () {
show_img_containers ( $section );
}
);
}
);
}
$( document ).ready(
function ( $ ) {
img_container = $( '.img_container' );
hide_img_containers ();
load_images();
}
);
}
)( jQuery, this );
.img_container {
min-height: 250px;
position: relative;
}
.img_container:before {
content: '';
display: block;
width: 100%;
height: 100%;
top: 0;
left: 0;
position: absolute;
}
#sec_1:before {
background-image: url(http://www.lifeofpix.com/wp-content/uploads/2017/03/dscf0786.jpg), linear-gradient(to top, #206020, #fff);
background-size: cover, cover;
}
#sec_2:before {
background-image: url(http://www.lifeofpix.com/wp-content/uploads/2017/03/dscf0357.jpg), linear-gradient(to top, #206020, #fff);
background-size: cover, cover;
}
#sec_3:before {
background-image: url(http://www.lifeofpix.com/wp-content/uploads/2016/05/Life-of-Pix-free-stock-street-lights-wall-PaulJarvis.jpg), linear-gradient(to top, #206020, #fff);
background-size: cover, cover;
}
#sec_4:before {
background-image: url(http://www.lifeofpix.com/wp-content/uploads/2017/03/1-276.jpg), linear-gradient(to top, #206020, #fff);
background-size: cover, cover;
background-position: 50% 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="sec_1" class="img_container" data-img="http://www.lifeofpix.com/wp-content/uploads/2017/03/dscf0786.jpg"></section>
<section id="sec_2" class="img_container" data-img="http://www.lifeofpix.com/wp-content/uploads/2017/03/dscf0357.jpg"></section>
<section id="sec_3" class="img_container" data-img="http://www.lifeofpix.com/wp-content/uploads/2016/05/Life-of-Pix-free-stock-street-lights-wall-PaulJarvis.jpg"></section>
<section id="sec_4" class="img_container" data-img="http://www.lifeofpix.com/wp-content/uploads/2017/03/1-276.jpg"></section>

Use a CSS transformation on an entire page including fixed backgrounds (in Firefox)

I've made a script that re-sizes my website with some ratio: 'rat'. I do a scale but that scale creates white margins so I transform the entire html page and I sent it to origin in the coordinates 0 , 0.
document.documentElement.style.transform = "scale(" + rat + ")";
document.documentElement.style.width = 100 / rat + "%";
document.documentElement.style.transformOrigin = '0 0';
The problem I have is that some background images with the following property do not transform:
background-attachment: fixed;
Everytime I transform my html page the background images with background-attachment: fixed; don't transform.
You can check what I'm talking about in my portfolio here:
http://testedesignfranjas.tumblr.com/
Open the site in chrome and in FIREFOX and see the differences.
The issue is in Firefox.
*sorry for my bad english
I have a partial answer. Firefox doesn't always treat nested, fixed elements correctly when using a transform. Instead of using background-attachment, make the div with the image position:fixed. The second div is relative or static, so it will overlay the first div.
<body onload="scaleAll(0.8)">
<div id="img1">I have a background image, am scaled and am fixed.</div>
<div id="outer">
I have content and am scaled.
</div>
</body>
I have moved the image outside the div and set img1 to position:fixed. Do the scaling individually, once for img1 and once for the outer div that has the content.
<script>
function scale(rat, container) {
var element = document.getElementById(container);
element.style.transform = 'scale(' + rat + ')';
element.style.transformOrigin = '0 0';
}
function scaleAll(rat) {
scale(rat, "outer");
scale(rat, "img1");
}
</script>
The style uses position:fixed for the img1 and relative for the outer.
<style>
div#outer {
position: relative;
height: 900px;
width: 900px;
}
#img1 {
position: fixed;
background: url("image.png") no-repeat;
width: 796px;
height: 397px;
}
</style>
JSFiddle Example
Use jQuery to remove the "fixed" attribute when you scale document
$("img").each(function() {
$(this).css("background-attachment","");
});

Jquery not adding an background image to div

I have a function that is adding a background-image to my div. But its not showing.
this is my function
var totalCount = 6;
function changeBackground()
{
var num = Math.ceil( Math.random() * totalCount );
backgroundUrl = '/background/test2/'+num+'.jpg';
$('#background').css('background-image, url(' +backgroundUrl+ ')');
}
changeBackground();
The image changes everytime that the the page gets refreshed. I know that part is working because if i change
$('#background').css('background-image, url(' +backgroundUrl+ ')');
to
document.body.parentNode.style.backgroundImage = 'url(background/test2/'+num+'.jpg)';
it shows me the image like i wanted. But on the html tag. I want it on the div, so i can fade it in with jQuery.
here is my CSS
#background {
width:100% !important;
height:100% !important;
background-repeat:no-repeat;
background-position:center center;
background-attachment:fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
i don't get any error's in the console and when i look up the css nothing is added in the css. How can i now what is wrong? So in the future i can for myself what the problem is.
Change
$('#background').css('background-image, url(' +backgroundUrl+ ')');
To
$('#background').css('background-image', 'url(' +backgroundUrl+ ')');

Categories

Resources