how to set div height as background image? - javascript

What I'm trying to achieve is that the height of the DIV will change depending on the image size (without repeat)I'm looking for a solution with broad browser support,I have already tried almost every answer I found on Google, nothing really worked
<!DOCTYPE html>
<html>
<head>
<style>
#div_1 {
width: 250px;
height: 250px;
background-image: url("https://i.ibb.co/YRwty0q/11.jpg");
}
#div_2 {
width: 250px;
height: 250px;
background-image: url("https://i.ibb.co/khjZcj2/222.jpg");
}
</style>
</head>
<body>
<div id="div_1"></div>
<div id="div_2"></div>
<script>
</script>
</body>
</html>

Load the image with Javascript:
$('div').each(function() {
const url = getComputedStyle($(this)[0])['background-image'].slice(5, -2)
const img = new Image()
img.src = url
img.onload = () => {
$(this).css({
width: img.width,
height: img.height
})
}
})
#div_1 {
background-image: url("https://i.ibb.co/YRwty0q/11.jpg");
}
#div_2 {
background-image: url("https://i.ibb.co/khjZcj2/222.jpg");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div_1"></div>
<div id="div_2"></div>

Related

Scrollbar height indicator to execute function

I'm using jQuery to get user's current height, and after he reaches that height, there will be animation function (Such as reactive websites, when user scroll down he has animation in different part of the page).
Yet, I can't really figure out why exactly the following code doesn't work.
$(window).scroll(function() {
var height = $(window).scrollTop();
if(height > 200) {
$("#project").animate({
bottom: '250px',
opacity: '0.5',
height: '1000px',
width: '100%'
});
}
});
CSS:
/* About Page */
.about{
width: 100%;
height: 1000px;
background-color: blue;
}
/* Projects Page */
.project{
background-color: red;
}
HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="jquery-3.4.1.min.js"></script>
<script src="myscripts.js"></script>
<title>My Portfolio</title>
</head>
<body>
<div id="about" class="about">
</div>
<div id="project" class="project">
</div>
</body>
</html>
How can I use scrolling height indicator to activate functions such as animation?
You need to take into account the height of each section and calculate the scrollBottom position instead, which might be more useful if you want to trigger an animation once you reach some element:
const $about = $('#about');
const $projects = $('#projects');
const $services = $('#services');
// Calculate the top offset of each section (number of sections above it * 1000px each).
// We want to expand them when we are 50px above them, so we substract that.
let projectTop = 1000 - 50;
let servicesTop = 2000 - 50;
$(window).scroll(() => {
requestAnimationFrame(() => {
// Calculate the scrollBottom by summing the viewport's height:
const scrollBottom = $(window).scrollTop() + $(window).height();
if (scrollBottom >= projectTop) {
$projects.animate({ height: '1000px' });
}
if (scrollBottom >= servicesTop) {
$services.animate({ height: '1000px' });
}
});
});
body {
margin: 0;
}
.about {
background: red;
width: 100%;
height: 1000px;
}
.projects {
background: green;
width: 100%;
}
.services {
background: blue;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="about" class="about"></div>
<div id="projects" class="projects"></div>
<div id="services" class="services"></div>

Function on resize doesn't work

Hello I have problem with really easy script. It should change class if under 768 px of window width but it just doesn't work. I have no clue why. I dont want to use media queries in this in this case.
Here's code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>ez</title>
<style>
.aside {
float: left;
height: 1000px;
width: 250px;
background-color: grey;
}
.sidebar {
position: absolute;
top: 0;
left: -250px;
}
</style>
</head>
<body style="height: 2000px">
<aside class="aside" id="aside"></aside>
<main style="float: left; height: 1000px; width: 70%; background-color: black;"></main>
<script>
var elm = document.getElementById("aside");
function change() {
var w = window.innerWidth;
if(w<768) {
elm.className = "sidebar";
} else {
elm.className = "aside";
}
}
window.addEventListener("resize", change);
</script>
</body>
</html>
I started your script. For 768px and more there is class 'aside', for 767px and less class 'sidebar'. So where is the problem?
If you open page on width less than 768 your script won't be working correct. You have to add it to event onload too

Background Image that covers whole webpage, is responsive and also is chosen randomly

I am trying to create a page that has a background image that uses the css cover property so that it is responsive in the browser but doesn't get distorted but is chosen by random from an array in jQuery.
I don't have much code because this is the only thing that I am doing at the moment, I've been playing around but I don't have much of a handle on jQuery so I don't really know what I am doing! Any help appreciated!
HTML:
<head>
<title>Test</title>
<link href="css/css.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="javascript/jquery.js"></script>
</head>
<body>
<div id="background">
</div>
</body>
CSS:
body {
margin: 0;
}
#background {
width: 100%;
height: 100%;
margin: 0;
background-repeat: no-repeat;
background-size: cover;
background-image: url(backgroundImage)
}
html, body {
overflow: none !important;
overflow-x: none !important;
overflow-y: none !important;
}
jQuery:
var picArr = ['Images/IMG_3764.jpg', 'Images/IMG_3793.jpg', 'Images/IMG_4050.jpg', 'Images/IMG_4323.jpg', 'Images/IMG_4351.jpg', ];
var myNumber = Math.floor(Math.random() * 5);
$(document).ready(function () {
$("background-image").attr('url', picArr[myNumber]);
});
If you want to randomise it, use a setTimeout()
Also, to change the background image on the "background" div, just .css jquery selector like below.
eg
var picArr = ['Images/IMG_3764.jpg', 'Images/IMG_3793.jpg', 'Images/IMG_4050.jpg', 'Images/IMG_4323.jpg', 'Images/IMG_4351.jpg', ];
$(document).ready(function () {
setTimeout(function(){
var myNumber = Math.floor(Math.random() * 5) + 1;
$("#background").css('background-image', 'url('+picArr[myNumber]+')'); //here
}, 3000); // ms of how often you want it to change.
});
Didn't you misstype the selector $("background-image"), isn't this supposed to be $("#background")
var picArr = ['Images/IMG_3764.jpg', 'Images/IMG_3793.jpg', 'Images/IMG_4050.jpg', 'Images/IMG_4323.jpg', 'Images/IMG_4351.jpg', ];
var myNumber = Math.floor(Math.random() * 5);
$(document).ready(function () {
$("#background").attr('url', picArr[myNumber]); //here
});
#background {
width: 100%;
height: 100%;
margin: 0;
background-repeat: no-repeat;
background-size: cover;
background-image: url(backgroundImage)
}
<link href="css/css.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="javascript/jquery.js"></script>
<div id="background">
</div>
I guess this has already been answered now but this was my solution:
var picArr = ['http://lorempixel.com/output/fashion-q-c-640-480-1.jpg', 'http://lorempixel.com/output/animals-q-c-640-480-4.jpg', 'http://lorempixel.com/output/nightlife-q-c-640-480-2.jpg'];
var l = picArr.length;
var myNumber = Math.floor(Math.random() * l);
console.log(myNumber);
$(document).ready(function () {
$("#background").attr('style', 'background: url(' + picArr[myNumber]) + ')';
});
CSS:
html, body {
margin: 0;
height: 100%;
min-height: 100%;
}

JS (CSS) dynamic background image moving

I made up a little script that makes a photo background to scroll up/button in same time with page scrolling. The problem is that the background image is scrolling after the page was scrolling (it have a delay).
Question: How may I make to move background image with page scrolling like in this example http://shapebootstrap.net/item/1524936-unika-responsive-one-page-html5-template/live-demo ?
I made a plnkr with my code: https://plnkr.co/edit/e6OCUF4sXSA80Pi6XANj?p=preview
var bgScroll = function(lastScrollTop, elem) {
lastScrollTop = $(window).scrollTop();
$(elem).css('transition', 'all .5s');
$(elem).css('background-position', '0% ' + parseInt(-lastScrollTop / 2) + 'px');
console.log('lastScrollTop = ' + lastScrollTop);
};
$(window).load(function() {
var lastST = 0;
var homeElem = '#add-outer-container';
$(window).on("scroll", function() {
bgScroll(lastST, homeElem);
});
});
html,
body {
height: 100%;
margin: 0;
padding: 0;
background-color: gray;
}
#add-outer-container {
width: 100%;
height: 500px;
background: #fff url(http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg) no-repeat fixed 0% 0%;
overflow: hidden;
color: white;
border: 1px solid red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- version 0.6.1.0 -->
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" type="text/css" href="app.css"></link>
</head>
<body>
<div id="add-outer-container"></div>
<div style="height: 1500px; color: green;"></div>
</body>
</html>
What your are looking for is called parallax effect. There are several libraries which can help you (http://pixelcog.github.io/parallax.js/ for instance). But the simplest solution could something like this:
// Handle the window scroll event
$(window).scroll(function () {
// Store the distance scrolled
var scrolled = $(window).scrollTop() + 1;
// Set the scroll speed
var scrollSpeed = 0.3;
// Update the background position
$("#add-outer-container").css('background-position', '0' + -(scrolled * scrollSpeed) + 'px');
});
body {
min-height:3000px;
}
#add-outer-container {
background:url(http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg) no-repeat fixed;
width:100%;
height:500px;
margin:0 auto;
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="add-outer-container"></div>
1- from JS remove the line: $(elem).css('transition', 'all .5s');
2- in your CSS add to #add-outer-container class:
transition: all 0.5s;
transition-timing-function:cubic-bezier(0,0,0.2,1);

Jquery: show IMG on click

Preview of how it should be: https://www.youtube.com/embed/8qKRf0cg3Co
As in the video, I have to click on the img to get a large view of the img under it.
So far this is my code:
HTML:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>JQUERY</title>
<script src="jquery/jquery-2.1.1.min.js"></script></head>
<body>
<center>
<div id="wrapper">
<div id="nav">
<div id="overbalk"></div>
<img src="images/foto_01.png" align="top" class="foto" />
<img src="images/foto_02.png" align="top" class="foto" />
<img src="images/foto_03.png" align="top" class="foto" />
<img src="images/foto_04.png" align="top" class="foto" />
</div>
<div id="content">
<img src="images/foto_01.png" align="top" class="slide_foto" />
</div>
</div>
</center>
</body>
</html>
CSS:
<style>
body {
padding: 0;
margin: 0;
background-color: black;
}
#nav {
width: 600px;
margin: 0px auto;
}
#overbalk {
width: 600px;
height: 30px;
position: absolute;
background-color: black;
}
.foto {
width: 75px;
height: 75px;
margin-top: -20px;
border: 1px solid black;
}
.foto:hover {
cursor: pointer;
}
#content {
position: absolute;
top: 50px;
z-index: -2;
width: 100%;
}
.slide_foto {
margin-left:-3200px;
}
</style>
JS:
$(document).ready(function (){
$('.foto').mouseenter(function () {
$(this).animate({marginTop: '+=50'}, 200);
});
$('.foto').mouseleave(function (){
$(this).animate({marginTop: '-=50'}, 200);
});
$('.foto').click(function () {
$(this).next('#content').show();
});
});
I also tried this:
$('.foto').on('click', function () {
$('#content').html(nieuwe_foto).show();
var nieuwe_foto = $(this).attr('src');
$('.slide_foto').attr('src', nieuwe_foto);
}
None of this worked, and got a little bit stuck, the images aren't showing below the small images.
You need to make 2 changes:
Remove this style class from <style>
.slide_foto {
margin-left:-3200px;
}
Make this change in your onclick handler
$('.foto').on('click', function () {
var nieuwe_foto = $(this).prop('src');
$('.slide_foto').prop('src', nieuwe_foto);
});
I have made a working fiddle with sample images https://jsfiddle.net/sachin_puthran/c2qgjpj1/
The following doesn't do anything since nieuwe_foto is undefined until the next line and div#content is already visible .show() doesn't do anything either.
$('#content').html(nieuwe_foto).show();
The .show() isn't what you're looking for. It will essentially "unhide" an element. So if an element has a display: none style then .show() will restore the initial display style. See the docs.
You're closer with your second attempt though. All you want to do in the $('.foto').click function is set the src of the .slide_foto element to what is currently in the src of the this object.

Categories