How to change HTML background with JavaScript Function? - javascript

How to change HTML background with JavaScript Function? I need some simple function to change background from one image to another?

Try something like this:
function newBackGround (element,background) {
element.style.backgroundImage = "url("+background+")";
}
newBackground (myElement,"newBackground.jpg");

An alternative IFF using jquery
$("body").css("background-image", "url(/image.jpg)");

Very simple like this:
function changeBGImage(){
document.body.background = "image.jpg";
}
UPDATE
Or if you wanna use CSS (more elegant solution) with it, you could use:
<style>
.bg1 {
background-image: url(images/my_image.jpg);
}
</style>
<body id="page_body">
<script>
function changeBGImage(whichImage){
document.getElementById('page_body').className="bg"+whichImage;
}
</script>

demo codes:
element = document.querySelector("body");
element.style.backgroundImage = "url('https://cdn.xgqfrms.xyz/logo/logo.png')";
elements = document.querySelectorAll("div");
for(let element of elements){
element.style.background = "url('https://cdn.xgqfrms.xyz/logo/logo.png')";
}
reference links:
http://www.w3schools.com/jsref/dom_obj_style.asp
http://www.w3schools.com/jsref/prop_style_background.asp
http://www.w3schools.com/jsref/prop_html_style.asp
http://www.w3schools.com/jsref/met_document_queryselectorall.asp
http://www.w3schools.com/jsref/met_document_queryselector.asp
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll

function changeBGImage(whichImage){
document.body.style.backgroundImage = "url(" + whichImage + ")";
}

All of these answers change the body. The most direct way to change the html background is like so:
const imagePath = "/img/sub-folder/my-image.png";
document.documentElement.style.background = `url("${imagePath}")`;

Related

onmouseover function Javascript for changing the background of a section

I was trying to write a function that changes the color of background of a section by going over it with the mouse - using 'onmouseover'. I was looking for similar question and tried the solutions that was offered but it did not work on my code.
Here is what i did:
function Rectangle(count){
var newRec = document.createElement("SECTION");
newRec.style.width="202px";
newRec.style.height="312px";
newRec.style.border="1px solid #3f3f3f";
newRec.style.background = "#FFFFFF";
newRec.style.display = "inline-block";
newRec.style.margin= "44px";
newRec.style.size= "50px";
var appendRec = function() {
document.addEventListener("onmouseover", myFunction);
document.getElementsByTagName('main')[0].appendChild(newRec);
};
function myFunction() {
document.getElementTagName("SECTION").style.background = "#000000";
};
appendRec();
};
Can anyone tell me what i did wrong?
And I was trying to work with the console but this code doesn't say anything is wrong...
document.getElementTagName("SECTION").style.background = "#000000"; is wrong.
First, it's called getElementsByTagName(). And second, it returns an array, not just one element.
Solution: Give the <section> an id and use getElementById() instead.
You just need
document.getElementById('WhichElementWillBeHoveredID').onmouseenter = function() {
// when entering element...
}
document.getElementById('WhichElementWillBeHoveredID').onmouseleave = function() {
// when leaving element
}
Sure... you can easily use CSS as well..
SELECTOR:hover { background-color: #444 }
I created a fiddle to change background color and this is the only requirenment then I think it is good
http://jsbin.com/cagawa/edit?html,css,output
#mydiv{
background: #cccccc;
}
#mydiv:hover{
background: #ffdd00;
}
try change
var appendRec = function() {
document.addEventListener("onmouseover", myFunction);
document.getElementsByTagName('main')[0].appendChild(newRec);
};
to
var appendRec = function() {
document.getElementsByTagName('main')[0].appendChild(newRec);
newRec.addEventListener("mouseover", myFunction);
};
I edited littlebit code, try now :)
If im not wrong on line 12:
document.addEventListener("onmouseover", myFunction);
should be replaced by
document.addEventListener("onmouseover",myFunction());

How can we make Image Carousel with background Image Property

I'm making an image carousel i'm bounded to use background-image property instead of using
<img src="Image">
tag. my carousel is working if I use img tag . But its not working when I use background-image property, how can I modify my code with background-image property.
see my fiddle :https://jsfiddle.net/korLasen/ and update it please thanks :)
or you can see code here
(function(){
var image = $('#imageSlider');
var imageSet = ['http://www.exposureguide.com/images/top-ten-tips/top-ten-photography-tips-1e.jpg','http://images.clipartpanda.com/cliparts-images-aTqyrB8TM.png'];
var index = 0;
function imageSliderSet(){
image.setAttribute('data-background', imageSet[index]);
index++;
if(index >= imageSet.length){
index = 0;
}
}
setInterval = (imageSliderSet, 2000);
})();
This is quite a strange question... however, I am not one to judge :)
Here is a jsfiddle based on your example. I ended up using jquery for this. I hope this is somewhere near what you were looking for!
This is based on changing every two seconds. To extend that, you can change line 18 in the jquery. Here is the jquery:
$( document ).ready(function(){
var image = $('#imageSlider');
var imageSet = ['http://www.exposureguide.com/images/top-ten-tips/top-ten-photography-tips-1e.jpg','http://images.clipartpanda.com/cliparts-images-aTqyrB8TM.png'];
var index = 0;
window.setInterval(function(){
image.css('background-image', "url('" + imageSet[index] + "')");
index++;
if(index >= imageSet.length){
index = 0;
}
//here you can adjust the time interval for each photo
}, 2000);
});

Change beginning of each image src with Javascript?

I am trying to use Javascript to change the beginning of each image src before the page loads.
I would want to change
src="v/image1.jpg"
src="v/image2.jpg"
src="v/image2.jpg"
to
src="http://different-server.com/v/image1.jpg"
src="http://different-server.com/v/image2.jpg"
src="http://different-server.com/v/image3.jpg"
Is there any way of doing that to all of the images of a certain class? Or would I have to create a loop that does this?
Thank you.
You may do like this:
var srcElement = document.getElementsByClassName('your_class');
for(var i=0;i<srcElement.length;i++){
srcElement[i].src = "http://different-server.com/" + srcElement[i].src
}
This code works :
$.each($("img"), function( index, value ) {
srcValue = "http://different-server.com/" + $(this).attr("src")
$(this).attr("src", srcValue)
});
See jsFiddle : http://jsfiddle.net/wkf3cpe9/

Javascript onMouseover to swap images

I have some code that makes an image larger when moused over:
<script>
function bigImg(x)
{
x.style.height="70px";
x.style.width="237px";
}
function normalImg(x)
{
x.style.height="56px";
x.style.width="218px";
}
</script>
and I call those functions with:
<a><img border="0" src="category_icons/addorder.png" onmouseover="bigImg(this)" onmouseout="normalImg(this)"></a>
But what I would really like to do is make it so the bigIMG(x) function also changes the image. I'm not extremely familiar with javascript and was wondering if someone knew what I can code in, to swap the image. The image name is addorder2.png. I've tried using this.src="addorder2.png"; but that is not working.
This will do. Change the image src into "addorder2.png".
<script>
function bigImg(x)
{
x.style.height="70px";
x.style.width="237px";
x.src = "addorder2.png";
}
function normalImg(x)
{
x.style.height="56px";
x.style.width="218px";
x.src = " addorder.png";
}
</script>
My 2 cents:
LIVE DEMONSTRATION
Don't use inline JS, rather you can set a data.* attribute
and an object literal that will contain your desired changes
and read it with JS:
<img class="zoom" src="img.jpg" data-enlarge='{"src":"img2.jpg", "zoom":"1.2"}'>
As you can see above we'll target with JS every element with class "zoom"
function enlarge(){
var el = this,
src = el.src,
data = JSON.parse(el.dataset.enlarge);
el.src = data.src;
el.style.transition = "0.3s";
el.style.transform = "scale("+data.zoom+")";
el.addEventListener('mouseleave', function(){
el.src = src;
el.style.transform = "scale(1)";
},false);
}
var $ZOOM = document.querySelectorAll('.zoom');
for(var i=0; i<$ZOOM.length; i++){
$ZOOM[i].addEventListener('mouseenter', enlarge, false);
}
With Javascript you can edit the src attribute of the img.
Javascript:
function bigImg()
{
document.getElementById("myImg").src="addorder2.gif";
}
HTML:
<!DOCTYPE html>
<html>
<body>
<img id="myImg" onmouseover="bigImg()" src="addorder.png">
</body>
</html>
I recommend checking out w3schools to learn more about image document manipulation and of course specifically getting and setting the image src element
Just change x.src property according to function:
function bigImg(x)
{
x.style.height="70px";
x.style.width="237px";
x.src = "category_icons/addorder2.png";
}
function normalImg(x)
{
x.style.height="56px";
x.style.width="218px";
x.src = "category_icons/addorder.png";
}

Linking background colour change [css] to background image change [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();
});

Categories