Random background image for a webpage - javascript

I am trying to find a way that I can have an image that takes up the whole browser window and is responsive. Every time the page is loaded I would like the background image to change from a select group of photos that I have locally.
I have tried a few solutions on here but nothing is really working. The HTML I have is:
<div id="container">
<img src="Images/IMG_3764.JPG" alt="An island in the middle of the sea in Turkey" id="backgroundImage">
</div>
The CSS I have is:
body {
margin: 0;
}
#container {
width: 100%;
height: 100%;
margin: 0;
}
#backgroundImage {
width: 100%;
position: fixed;
top: 0;
left: 0;
}
html, body {
overflow: none !important;
overflow-x: none !important;
overflow-y: none !important;
}
One of the JS solutions that I have tried is this:
var image = new Array ();
image[0] = "http://placehold.it/20";
image[1] = "http://placehold.it/30";
image[2] = "http://placehold.it/40";
image[3] = "http://placehold.it/50";
var size = image.length
var x = Math.floor(size*Math.random())
$('#backgroundImage').attr('src',image[x]);

Your going to need to have an array of images stored in JavaScript like so:
var picArr = [imageSrc1 ,imageSrc2 ,imageSrc3];
After which you'll need some kind of random number that conforms to the amount of image src's you have in the above array.
http://www.w3schools.com/jsref/jsref_random.asp
You'll be using Math.random() here
Then you'll need to create a function that shall be executed when the document loads that changes the src of your background above.
Your final function might look like this:
var picArr = ['src0', 'src1', 'src2', 'src3', 'src4', 'src5', 'src6', 'src7', 'src8', 'src9', ];
var myNumber = Math.floor((Math.random() * 10) + 1);
$(document).ready(function () {
$("#backgroundImage").attr('src', picArr[myNumber]);
});

With jquery you could do something like this
See jsfiddle here.
var images = ['http://farm5.static.flickr.com/4017/4717107886_dcc1270a65_b.jpg', 'http://farm5.static.flickr.com/4005/4706825697_c0367e6dee_b.jpg', 'https://s-media-cache-ak0.pinimg.com/originals/c6/8a/51/c68a5157020c8555ca781839d754a1a0.jpg'];
var randomImage = Math.floor(Math.random() * 3)
$(document).ready(function() {
$("#container").css("background-image", "url('" + images[randomImage] + "')");
})
html, body {
height: 100%;
}
#container {
background-repeat: no-repeat;
background-size: cover;
background-position: center;
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="container"></div>
</body>

Related

resizing images for slideshow

I'm trying to resize my images for a slideshow. When I plug them into an array and code them into a slideshow, the cropping is kind of off. I tried using object-position in CSS but that changes all the images in one shot and what works for one image doensn't necessarily work for others.
Here is the HTML:
<container class="main-img-cont">
<img class="main-img" alt="">
</container>
Here is the CSS:
.main-img-cont {
width: 100%;
height: 650px;
display: flex;
img {
width: 100%;
object-fit: cover;
object-position: 0 30%;
} // closes img
} // closes .main-img
Javascript:
window.onload = () => {
var mainImg = document.querySelector('.main-img');
let slideshow = [
'../img/jevon_cochran_pelourinho.jpg',
'../img/me_in_Pernambues.JPG',
'../img/quibdo_boat_ride.jpg'
];
var index = 0;
var interval = 1000;
function slide() {
mainImg.src = slideshow[index];
index++;
if (index >= slideshow.length) {
index = 0;
}
}
setInterval(slide, interval);
}

How to create a slideshow before showing the page?

I've been trying to find a way in order to create a slideshow and specify the timing between each picture. Then after the sequence, I want to display/reveal the home page.
I don't really have a lot of JavaScript experience so any help would be appreciated.
There are many ways to do it, here is one simple/basic example:
jQuery.fn.reverse = [].reverse; /* Just a helper */
var slideshowContainer = $('.slideshow');
var slideshowItems = slideshowContainer.find('.item').reverse();
var slideshowItemsTotal = slideshowItems.length;
slideshowItems.each(function(i) {
var thisItem = $(this);
setTimeout(function() {
thisItem.fadeOut(1000, function() {
thisItem.remove();
if( i+1==slideshowItemsTotal ) {
slideshowContainer.remove();
};
});
}, i*5000+4000);
});
* {
margin: 0 none;
box-sizing: border-box;
}
.slideshow {
position: fixed;
z-index: 10;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
}
.slideshow .item {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Page header</h1>
<p>Page content.</p>
<div class="slideshow">
<img class="item" src="http://placehold.it/800x600/00ff00/333" />
<img class="item" src="http://placehold.it/800x600/ff0000/111" />
</div>
Also on JSFiddle.
You should use setTimeout function to put timing between every function. Then change the pictures with functions to make it look like it is a slideshow.
Example: calls the function after 3 seconds to make an alert.
function myFunction() {
setTimeout(function(){ alert("Hello"); }, 3000);
}
You can find millions of examples on google for timing with JS.
Good luck

Create dynamic Rectangle collection in html using js

Hello All I am a beginner in html and js, and I am trying to create a webpage containing a rectangle collection in which when a new rectangle is created is placed beside the previous rectangle.
I have created a div element and trying to add newly created div (rectangle shape with background color different based on condition), but I am not able to get the desired result.
<html>
<head>
<title>parkIn</title>
<meta charset="utf-8" />
</head>
<style>
.ParkSlots {
border: solid 1px;
width: 60%;
height: 400px;
top: 50%;
left: 50%;
position: fixed;
transform: translate(-50%, -50%);
display: inline;
}
.row:before,
.row:after {
content: "";
display: table;
clear: both;
}
.col-1 {
width: 15%;
margin-left: 10px;
height: 350px;
padding: 2px;
}
</style>
<body onload="viewCreate()">
<div class="ParkSlots">
<div class="row" id="content">
</div>
</div>
</body>
<script language="javascript">
function viewCreate() {
for (int i = 0; i < 5; i++) {
if (i % 2 == 0) {
createGreenBox();
} else {
createRedBox();
}
}
}
function createRedBox() {
var = document.createElement('div');
div.className = 'col-1';
div.style.backgroundColor = 'red';
document.getElementById('content').appendChild(div);
}
function createGreenBox() {
var = document.createElement('div');
div.className = 'col-1';
div.style.backgroundColor = 'lightgreen';
document.getElementById('content').appendChild(div);
}
</script>
</html>
I want an output that looks something like this:
Just in glancing at your code, I see at least two typos:
for (int i = 0; i < 5; i++) { - in JS, int is not used in this way. Use var i = 0...
var = document.createElement('div'); - you're missing a variable name on this line in both create box functions. I assume, from the rest of the code you need var div = document.createElement('div');
The rest will be CSS. In your stylesheet you're applying the border to the outter most containing div, from you're example, you need to apply that to the .col-1 class. You'll also want to use display:inline-block on that class, and set widths and margins to play nicely with the border size. I took the liberty of creating a jsfiddle for you with my recommended changes.

How make a fade slideshow loop?

I am using javascript to change my css class background image every few seconds. It is working great the problem is it just stops after it shows the last image. Can anyone show me what to add to this code so that it will continuously loop itself?
$(window).load(function() {
$(document).ready(function() {
setInterval(fadeDivs, 5000); //call it every 2 seconds
function fadeDivs() {
var visibleDiv = $('.bckgnd:visible:first'); //find first visible div
visibleDiv.fadeOut(400, function() { //fade out first visible div
var allDivs = visibleDiv.parent().children(); //all divs to fade out / in
var nextDivIndex = (allDivs.index(visibleDiv) + 1) % allDivs.length; //index of next div that comes after visible div
var nextdiv = allDivs.eq(nextDivIndex); //find the next visible div
var lastDiv = $('.backgnd3');
var firstDiv = $('.backgnd1');
if (currentDiv != lastDiv) {
var nextdiv = allDivs.eq(nextDivIndex); //find the next visible div
} else {
var nextdiv = firstDiv; //the next div will be the first div, resulting in a loop
}
nextdiv.fadeIn(400); //fade it in
});
};
});
});
.backgnd1 {
width: 100%;
height: 452px;
background: url ('http://quaaoutlodge.com/sites/all/themes/marinelli/img/backgrounds/backgnd1.jpg');
background-size: cover;
background-repeat: no-repeat;
background-color: #000;
}
.backgnd2 {
width: 100%;
height: 452px;
background-image: url ('http://quaaoutlodge.com/sites/all/themes/marinelli/img/backgrounds/the_lodge.jpg');
background-size: cover;
background-repeat: no-repeat;
background-color: #000;
}
.backgnd3 {
width: 100%;
height: 452px;
background-image: url('http://quaaoutlodge.com/sites/all/themes/marinelli/img/backgrounds/getting_here.jpg');
background-size: cover;
background-repeat: no-repeat;
background-color: #000;
}
.index_roof_background {
background-color: #000;
width: 1600px;
height: 452px;
margin: 0px;
padding-top: 0px;
margin-left: auto;
margin-right: auto;
}
<div class="index_roof_background">
<div style="position:absolute; z-index: 2;display:block; background-color:#000;" class="bckgnd backgnd1"></div>
<div style="position:absolute; z-index: 2;display:none; background-color:#000;" class="bckgnd backgnd2"></div>
<div style="position:absolute; z-index: 2;display:none; background-color:#000;" class="bckgnd backgnd3"></div>
</div>
A better approach:
You don't need all those backgnd2 classes since you have only those DIVs inside a common parent.
Don't use inline styles! Use your stylesheet.
Don't use fixed width (px). Use % for responsive design.
2000*1331px images are
not suited for the web. Specially not for mobile devices. Care about
your user's bandwidth. When setting a background-image to cover you
don't need to worry about it being repeated.
Make your JS more flexible to element's indexes, count your elements using length.
Create a "current index counter", iterate over it increment it and
resetting using % (reminder).
For a better UX, allow the user to pause on hover.
Here's an eample:
jQuery(function($) { // DOM ready. $ alias in scope.
$('.gallery').each(function() {
var $gal = $(this),
$sli = $gal.find(">*"),
tot = $sli.length,
c = 0,
itv = null;
$sli.hide().eq(c).show(); // Hide all but first slide
function anim() {
c = ++c % tot; // increment/reset counter
$sli.fadeOut().eq(c).stop().fadeIn();
}
function play() {
itv = setInterval(anim, 3000);
}
function pause() {
clearInterval(itv);
}
$gal.hover(pause, play); // Pause on hover
play(); // Start loop
});
});
.gallery {
position: relative;
height: 200px;
}
.gallery>* {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: none 50%;
background-size: cover;
}
<div class="gallery">
<div style="background-image:url(http://placehold.it/800x600/0bf?text=1)"></div>
<div style="background-image:url(http://placehold.it/800x600/f0b?text=2)"></div>
<div style="background-image:url(http://placehold.it/800x600/0fb?text=3)"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First put the firstDiv, lastDiv in their own variables.
Then you will need something like this
if (currentDiv != lastDiv) {
var nextdiv = allDivs.eq(nextDivIndex); //find the next visible div
} else {
var nextdiv = firstDiv; //the next div will be the first div, resulting in a loop
}
nextdiv.fadeIn(400); //fade it in
Tell me if you need more help.
You need to use 2 timeouts to make it loop. A timeout only fires once. The FadeOutDivs function counts down, each time setting a timeout to call itself. Then at zero it fades sets a timeout the call fadeInDivs which start the whole cycle over.
I've got this running on codepen.
$(document).ready(function () {
var interval = 2000;
var fadeDuration = 400;
var allImages = $('.bckgnd');
var count = allImages.length - 1;
var imageCount = allImages.length;
setTimeout(fadeOutDivs, interval);
function fadeOutDivs() {
allImages.eq(count).fadeOut(fadeDuration);
console.log(count);
if (count > 1) {
count--;
setTimeout(fadeOutDivs, interval);
} else {
count = allImages.length - 1;
setTimeout(fadeInDivs, interval)
}
}
function fadeInDivs() {
allImages.fadeIn(fadeDuration);
setTimeout(fadeOutDivs, interval);
}
});

HTML5 and Javascript - a function appears to be working only once

guys, I am playing arround with HTML5 and javascript. The current thing which I am making is the following: there is a purple block on the screen and when you click a button it is moved 100 pixels to the right. This works so far, however, the function works only on the first time it is ran. I can't find my bug. I am posting the entire source code (javascript, html and css)
<!doctype html>
<head>
<style>
#stage{
position: relative;
width : 800px;
height : 600px;
background: #c0c0c0;
border: 1px dashed black;
}
.coil{
width: 64px;
height: 64px;
background: #800080;
position: absolute;
top: 200px;
left: 50px;
}
</style>
</head>
<body>
<div id="stage">
<div class="coil"></div>
<button id="button1">move!</button>
</body>
<script>
var coil = document.querySelector(".coil");
var button = document.querySelector("#button1");
button.addEventListener("click", clickHandler2, false);
//why is it working correctly just once
function clickHandler2()
{
coil.style.left += 100 + "px";
}
</script>
As nycynik mentioned, you are being a bit careless with the string additions.
Try this:
function clickHandler2()
{
var before = parseInt(coil.style.left);
before = isNaN(before) ? 0 : before;
coil.style.left = before + 100 + "px";
}
When you do your add like that, its not actually adding to the value, its only making a new string; add a console.log on the button and you will see.
console.log(coil.style.left += 100 + "px");
the output is "100px100px"
one alternative solution:
var coilPos = 100;
//why is it working correctly just once
function clickHandler2()
{
coilPos += 100;
coil.style.left = coilPos + "px";
console.log(coil.style.left += 100 + "px");
}
You must use a closure. A variable in the closure context must keep the left value. Then when applying the value to the property you use
var actualLeft += 100;
coil.style.left= actualLeft +"px";

Categories

Resources