Linking background colour change [css] to background image change [javascript] - javascript

I'm using the following code to change the background image when the page is refreshed
function changeImg(imgNumber) {
var myImages = ["../img/background_tile.png", "../img/background_tile_blue.png", "../img/background_tile_green.png", "../img/background_tile_purple.png"];
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
}
window.onload=changeImg;
Now I'm trying to make the CSS background-color change to the color of the image so that when the page is refreshed it doesn't flash white before it loads.
Website - http://lauramccartney.co.uk
Edit - I worked it out guys! I used this
function changeImg(imgNumber) {
var myImages = ["../img/background_tile.png", "../img/background_tile_blue.png", "../img/background_tile_green.png", "../img/background_tile_purple.png"];
var myColors = ["#d1261e", "#6167e6", "#3db322", "#a12cbb"];
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
document.body.style.backgroundColor = myColors[newImgNumber];
}
window.onload=changeImg;
Didn't make much of a difference so I also adjusted the background in the css to an inoffensive grey.

How about this :
Instead of just storing the img path, store it like color url('url-to-image'), and use that as the background while calling it.
So your array would look like : ['color1 url(url-1)', 'color2 url(url-2)', ...] and change the javascript to use document.body.style.background = array[array-index];
/*Makes background image change when refreshed*/
function changeImg(imgNumber) {
var myImages = ["red url(../img/background_tile.png)", "blue url(../img/background_tile_blue.png)", "green url(../img/background_tile_green.png)", "orange url(../img/background_tile_purple.png)"];
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.background = myImages[newImgNumber];
}
window.onload=changeImg;

It's always better to delegate styling to css classes, like this:
theme.css:
.theme-1 {
background:red url(../img/background_tile.png);
}
.theme-2 {
background:green url(../img/background_tile_green.png);
}
.theme-3 {
background:orange url(../img/background_tile_purple.png);
}
apply-theme.js:
/* Apply random class to body */
function setRandomTheme() {
var styles = ["theme-1", "theme-2", "theme-3"],
random = Math.floor(Math.random() * styles.length);
document.body.className += ' ' + styles[random];
}
And if you want to change background instantly, without flash of unstyled content, call setRandomTheme right before closing body tag:
<body>
<p>La-la-la, some content</p>
… skipped some code …
<script type="text/javascript">setRandomTheme();</script>
</body>
Or from DOMContentLoaded event:
just add this to apply-theme.js after setRandomTheme declaration:
document.addEventListener('DOMContentLoaded', function () {
setRandomTheme();
});

Related

How to make the background image change without a button with HTML & Javascript

I'm trying to make the background image change without a button, with any click in the back but its not working.
I tried to set the default background image defined in the CSS:
background-image: url('https://img.wallpapersafari.com/desktop/1920/1080/63/70/jE2ups.jpg');
And use this JavaScript, but once the imagen change I cant go back to the old one.
function myFunction() {
document.body.style.backgroundImage = "url('https://raw.githubusercontent.com/hxst1/hxst1.github.io/main/img/p2.jpg')";
}
Also tried $document on click but im new at this and its not working either.
If you want to toggle between 2 images it can easily be done by toggling a class on the body
document.addEventListener('click', () => {
document.body.classList.toggle("bgr");
})
body {
background-image: url('https://img.wallpapersafari.com/desktop/1920/1080/63/70/jE2ups.jpg');
}
.bgr {
background-image: url('https://raw.githubusercontent.com/hxst1/hxst1.github.io/main/img/p2.jpg') !important;
}
Like Spectric commented you can toggle background image:
document.addEventListener('click',function (){
document.body.classList.toggle('body_change');
})
.body_change {
background-image: url('https://picsum.photos/300');
}
body {
background-image: url('https://picsum.photos/200');
}
<body>
</body>
try that:
document.addEventListener('click',function myBackground(){
document.body.style.backgroundImage = "url('https://raw.githubusercontent.com/hxst1/hxst1.github.io/main/img/p2.jpg')";
})
if you want to automatic change every 1,2,3 or any seconds, you can try this way.
document.addEventListener('click',function myBackground(){
changeBackground();
})
let images = [
'https://images.unsplash.com/photo-1485322551133-3a4c27a9d925?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80',
'https://images.unsplash.com/photo-1507842217343-583bb7270b66?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=853&q=80',
'https://images.unsplash.com/photo-1600498148212-62bd3542ed63?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80',
'https://images.unsplash.com/photo-1611091428036-e0211d8016f0?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=745&q=80',
'https://images.unsplash.com/photo-1600431521340-491eca880813?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80'
];
let index = 0;
function changeBackground(){
document.body.style.backgroundImage = "url('"+images[index]+"')";
index = (index < images.length-1) ? (index+1) : 0;
}
// change backgroubd every 3 seconds
var interval = window.setInterval(function(){
changeBackground()
}, 3000); // 1000 = 1 second
// function to stop interval
// clearInterval(interval)
<h3>
change background
</h3>
It sounds like you are trying to toggle an image so you set the background image in css then switched it in javascript but forgot to write in the javascript the conditional statements (if/else). Basically if background is the first picture then change it to the second picture else change to first picture. Your code only says to change it to second picture.
function background(){
var body = document.body;
if(body.style.backgroundImage = "url('pic1')"){
body.style.backgroundImage = "url('pic2')";
} else {
body.style.backgroundImage = "url('pic1')";
}
}

Javascript/ I am stuck with changing back to the original background

I am learning JavaScript and am now doing a homework assignment.
I need to find how to remve a background image from an element after the mouse leaves the element.
I wrote the function code, Dogimgleave(), and it does not update the HTML.
Here is the code, please help me...
<img class=size src = "Images/Dog.jpg" alt="Dog!" onmouseover="Dogimgon()" onmouseleave="Dogimgleave()">
function Dogimgon(){
document.getElementById("centertext").style.backgroundImage="url('Images/Dog.jpg')";
}
function Dogimgleave() {
document.getElementById("centertext").style.backgroundColor="#65F0B6";
}
You're leaving the background image set as an image, so you won't see the background colour. You can clear the image like this...
function Dogimgleave() {
var ct = document.getElementById("centertext");
ct.style.backgroundImage = ""; // this removes the background image
ct.style.backgroundColor="#65F0B6";
}
If you set the backogrund-image and background-color simultaneously one will cover the other one. You should have only one of them set at any time:
var elem = document.getElementById("centertext");
function Dogimgon(){
elem.style.backgroundImage = "url('Images/Dog.jpg')";
elem.style.backgroundColor = "";
}
function Dogimgleave() {
elem.style.backgroundImage = "";
elem.style.backgroundColor = "#65F0B6";
}
This can be of course simplified to setting just the background property:
var elem = document.getElementById("centertext");
function Dogimgon(){
elem.style.background = "url('Images/Dog.jpg')";
}
function Dogimgleave() {
elem.style.background = "#65F0B6";
}
Or alternatively you may have color always set (it would be visible through transparent parts of the image however) and alter only the image:
var elem = document.getElementById("centertext");
elem.style.backgroundColor = "#65F0B6";
function Dogimgon(){
elem.style.backgroundImage = "url('Images/Dog.jpg')";
}
function Dogimgleave() {
elem.style.backgroundImage = "";
}
By the way, unless you task is to do that exactly in JavaScript, you may easily achieave the same result with pure CSS:
#centertext {
background: #65f0B6;
}
#centertext:hover {
background: url('/Images/Dog.jpg');
}

Setting background image from array isn't working?

I created a random quote generator and I'm trying to set up the background image in a way that when a person click on "New Quote" button, the background image changes. I have created a function and added images array in it and animated the effect and tried to call it but it's not working...
Here's my code below. You can also see my full code at http://codepen.io/kikibres/pen/RKeNQg
function getImage() {
var backImages = ['https://s6.postimg.org/pk900j3a9/quoteimg1.jpg', 'https://s6.postimg.org/pyac04ndt/quoteimg2.jpg', 'https://s6.postimg.org/kbdz2nkv5/quoteimg3.jpg', 'https://s6.postimg.org/suxd0et7l/quoteimg4.jpg', 'https://s6.postimg.org/z9wdx2zxd/quoteimg5.jpg', 'https://s6.postimg.org/56hv54wo1/quoteimg6.jpg', 'https://s6.postimg.org/s98e4ay5d/quoteimg7.jpg', 'https://s6.postimg.org/8fwablkrl/quoteimg8.jpg', 'https://s6.postimg.org/rm9hes19d/quoteimg9.jpg', 'https://s6.postimg.org/85td5zvj5/quoteimg10.jpg'];
var randomImg = Math.floor(Math.random() * backImages.length);
var quoteImg = backImages[randomImg];
$(".wrapper").animate({opacity: 0}, speed, function() {
$(".wrapper").animate({opacity: 1}, speed);
$(".wrapper").css(
'background-image', 'url(' + quoteImg + ')');
});
};
$("#new-quote").text(getQuote);
$("#new-quote").on("click", getQuote);
$("#new-quote").on("click", getImage);
How do I get the background image to work every time I click "New Quote" button?
All you need is to define variable speed somewhere at start of script:
$(document).ready(function() {
var speed = 1000;
...
You just have to change the jQuery method, and the whole code at your link http://codepen.io/kikibres/pen/RKeNQg is fine
$("#new-quote").onload(getImage); //Wrong
$("#new-quote").on("load",getImage); //Use this

How to add the background css into this jQuery? [duplicate]

This question already has an answer here:
How to change the css attribute of #header using jQuery and an array of images?
(1 answer)
Closed 8 years ago.
As you can see in my fiddle here, http://jsfiddle.net/HsKpq/460/ I am trying to show the images into the
$('#header').css('background-image',..................).fadeTo('slow',1);
How can I do this?
var img = 0;
var imgs = [
'http://www.istockphoto.com/file_thumbview_approve/9958532/2/istockphoto_9958532-sun-and-clouds.jpg',
'http://www.istockphoto.com/file_thumbview_approve/4629609/2/istockphoto_4629609-green-field.jpg',
'http://www.istockphoto.com/file_thumbview_approve/9712604/2/istockphoto_9712604-spring-sunset.jpg'
];
// preload images
$.each(imgs,function(i,e){var i=new Image();i.src=e;});
// populate the image with first entry
$('img').attr('src',imgs[0]);
var opacity = 0.1; // change this for minimum opacity
function changeBg() {
$('img').fadeTo('slow',opacity,function(){
$('#header').css('background-image',..................).fadeTo('slow',1);
});
}
setInterval(changeBg,5000);
You can do it without img elements, using backgound css property, like here:
var img = 0;
var imgs = [
'http://www.istockphoto.com/file_thumbview_approve/9958532/2/istockphoto_9958532-sun-and-clouds.jpg',
'http://www.istockphoto.com/file_thumbview_approve/4629609/2/istockphoto_4629609-green-field.jpg',
'http://www.istockphoto.com/file_thumbview_approve/9712604/2/istockphoto_9712604-spring-sunset.jpg'
];
// preload images
$.each(imgs,function(i,e){var i=new Image();i.src=e;});
var img = imgs[0];
var opacity = 0.1; // change this for minimum opacity
function changeBg() {
$('#header').fadeTo('slow',opacity,function(){
$('#header').css('background-image', 'url(' + img + ')').fadeTo('slow',1);
});
}
setInterval(changeBg,5000);
Don't know what you were trying to do with the background image and then populating the first image to a non-existent element.
Here is an updated fiddle: http://jsfiddle.net/HsKpq/464/
But this may be what you are looking for to show the images :
var $h_image = $('#headerImage');
function changeBg() {
$h_image.fadeTo('slow',opacity,function(){
$h_image.attr('src', imgs[Math.floor((Math.random() * 3))]).fadeTo('slow',1);
});
}
You also need to change your HTML to this :
<div id="header"><img id="headerImage"/></div>

toggle body background

I hope someone can help me with this, I have this javascript code that toggles my body background
function changeDivImage() {
imgPath = document.body.style.backgroundImage;
if (imgPath == "url(images/bg.jpg)" || imgPath == "") {
document.body.style.backgroundImage = "url(images/bg_2.jpg)";
} else {
document.body.style.backgroundImage = "url(images/bg.jpg)";
}
}
I activate it with this link:
change
my problem is that it works fine in IE and firefox, but in chrome, the links work twice then stop working, it basically switches to bg_2.jpg then once clicked again switches back to bg.jpg then it never works again :/
also, is there an easier way to accomplish this? css only maybe? basically i have two body background pictures and i want to be able to click on the link to toggle 1, then click again to toggle 2 instead, then back to 1, etc...
lastly, how can i make the two backgrounds fade in and out? instead of just switch between the two?
Use CSS classes!
CSS Rules
body { background-image: url(images/bg.jpg); }
body.on { background-image: url(images/bg_2.jpg); }
JavaScript:
function changeDivImage() {
$("body").toggleClass("on");
}
If you want to fade, you will end up having to fade the entire page. Use can use jQuery's fadeIn and fadeOut.
Here is your solution:
(This also supports additional images).
var m = 0, imgs = ["images/bg.jpg", "images/bg_2.jpg"];
function changeDivImage()
{
document.body.style.backgroundImage = "url(" + imgs[m] + ")";
m = (m + 1) % imgs.length;
}
Here is the working code on jsFiddle.
Here is the jQuery version on jsFiddle.
UPDATE: CROSS-FADING Version
Here is the cross-fading jQuery version on jsFiddle.
You wouldn't want the whole page (with all elements) to fade in/out. Only the bg should fade. So, this version has a div to be used as the background container. Its z-depth is arranged so that it will keep itself the bottom-most element on the page; and switch between its two children to create the cross-fade effect.
HTML:
<div id="bg">
<div id="bg-top"></div>
<div id="bg-bottom"></div>
</div>
<a id="bg-changer" href="#">change</a>
CSS:
div#bg, div#bg-top, div#bg-bottom
{
display: block;
position: fixed;
width: 100%;
/*height: 500px;*/ /* height is set by javascript on every window resize */
overflow: hidden;
}
div#bg
{
z-index: -99;
}
Javascript (jQuery):
var m = 0,
/* Array of background images. You can add more to it. */
imgs = ["images/bg.jpg", "images/bg_2.jpg"];
/* Toggles the background images with cross-fade effect. */
function changeDivImage()
{
setBgHeight();
var imgTop = imgs[m];
m = (m + 1) % imgs.length;
var imgBottom = imgs[m];
$('div#bg')
.children('#bg-top').show()
.css('background-image', 'url(' + imgTop + ')')
.fadeOut('slow')
.end()
.children('#bg-bottom').hide()
.css('background-image', 'url(' + imgBottom + ')')
.fadeIn('slow');
}
/* Sets the background div height to (fit the) window height. */
function setBgHeight()
{
var h = $(window).height();
$('div#bg').height(h).children().height(h);
}
/* DOM ready event handler. */
$(document).ready(function(event)
{
$('a#bg-changer').click(function(event) { changeDivImage(); });
changeDivImage(); //fade in the first image when the DOM is ready.
});
/* Window resize event handler. */
$(window).resize(function(event)
{
setBgHeight(); //set the background height everytime.
});
This could be improved more but it should give you an idea.
There's a cleaner way to do this. As a demo, see:
<button id="toggle" type="button">Toggle Background Color</button>
var togglebg = (function(){
var bgs = ['black','blue','red','green'];
return function(){
document.body.style.backgroundColor = bgs[0];
bgs.push(bgs.shift());
}
})();
document.getElementById('toggle').onclick = togglebg;
http://jsfiddle.net/userdude/KYDKG/
Obviously, you would replace the Color with Image, but all this does is iterate through a list that's local to the togglebg function, always using the first available. This would also need to run window.onload, preferably as a window.addEventListener/window.attachEvent on the button or elements that will trigger it to run.
Or with jQuery (as I notice the tag now):
jQuery(document).ready(function ($) {
var togglebg = (function () {
var bgs = ['black', 'blue', 'red', 'green'];
return function () {
document.body.style.backgroundColor = bgs[0];
bgs.push(bgs.shift());
}
})();
$('#toggle').on('click', togglebg);
});
http://jsfiddle.net/userdude/KYDKG/1/
And here is a DummyImage version using real images:
jQuery(document).ready(function ($) {
var togglebg = (function () {
var bgs = [
'000/ffffff&text=Black and White',
'0000ff/ffffff&text=Blue and White',
'ffff00/000&text=Yellow and Black',
'ff0000/00ff00&text=Red and Green'
],
url = "url('http://dummyimage.com/600x400/{img}')";
return function () {
document.body.style.backgroundImage = url.replace('{img}', bgs[0]);
bgs.push(bgs.shift());
}
})();
$('#toggle').on('click', togglebg);
});
http://jsfiddle.net/userdude/KYDKG/2/

Categories