How can i change background image through js code? - javascript

I have background image installed in css:
.indicator {
grid-area: b;
background-color: yellow;
background-image: url(./maxresdefault.jpg);
}
and want to change it on event like that:
indicator.oncontextmenu = function() {
indicator.style.background = '';
alert('msg');
}
but have no clue which type of command is used to change the background image in css by js. how do i change it?

Try this:
indicator.addEventListener('contextmenu', () => {
indicator.style.backgroundImage = "url('your_image.png')";
alert('msg');
})

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')";
}
}

CSS Toggle Switch to add a class to a DIV with local storage

I'm trying to create a simple toggle switch to add a new class to the body tag. By default the page is red. By clicking the button the page is toggled between red and blue.
Here's the code I have so far - the Switch Colour button would then change the body class tag to blue
<body>
<p>Click the button to change the colour of page</p>
<button onclick="myFunction()">Change background colour</button>
<script>
function myFunction() {
var element = document.body;
element.classList.toggle("blue");
}
</script>
</body>
The CSS bit
body {
background-color: red;
color: white;
}
body.blue {
background-color: blue;
}
The bit I'm struggling with is to keep the settings when I refresh the page or move to another page. Is there a way to store this via Local Storage and javascript?
Thanks in advance,
Brian
For a more dynamic solution (what happens if you have more than two colors?), I would instead go with a CSS variable, where the default color is red. Stack Overflow doesn't allow reading from localStorage, so I will comment out that code, and instead use a variable for demo purposes.
I do think the code is self-explanatory.
const BACKGROUND_KEY = 'background';
var forDemoPurposeOnly = '';
function myFunction() {
let isBlue = readFromLocalStorage(BACKGROUND_KEY) == 'blue';
let color = (isBlue) ? 'red' : 'blue';
setBackgroundColor(color);
}
function setBackgroundColor(color) {
let root = document.documentElement;
root.style.setProperty('--user-selected-background', color);
setInLocalStorage(BACKGROUND_KEY, color);
}
function readFromLocalStorage(key) {
return forDemoPurposeOnly;
// return localStorage.getItem(key);
}
function setInLocalStorage(key, value) {
forDemoPurposeOnly = value;
// localStorage.setItem(key, value);
}
:root {
--background-color: var(--user-selected-background, red); /* defaults to 'red' */
}
body {
background-color: var(--background-color);
}
<body onload="setBackgroundColor(readFromLocalStorage('background'))">
<p>Click the button to change the colour of page</p>
<button onclick="myFunction()">Change background colour</button>
</body>
The local storage API is super simple to use. localStorage is available as a global in the browser, you can store a string value with a key and then retrieve the value with the key.
function myFunction() {
var element = document.body;
element.classList.toggle("blue");
var background = localStorage.getItem('background')
if (background === 'blue') {
localStorage.setItem('background', 'red')
} else {
localStorage.setItem('background', 'blue')
}
}
(function() {
var background = localStorage.getItem('background')
if (background === 'blue') {
document.body.classList.add(background)
}
})()

How to change multiple backgrounds in a Javascript file?

I have designed a game where In the first page I ask the name of the user( background used- bgimg1)
On the click of a certain button, I go to the next page(I changed the background again) What I tried to do this was background(bgimg2) and I also tried putting [changeImage and changeAnimation, no error and still did not work], so I tried putting bgimg = bgimg2, It worked!
Now I displayed another button, and on the click of the button I called a function (name - attack),
In the function I tried to use bgimg2 = bgimg3;
It did not work, what should I do to change the background again, please suggest how to change the background, I think maybe if I preload all the images in the same variable, then how will I display different backgrounds in different functions;
Code
function preload() {
bgimg = loadImage("images/LayoutGH.png");
bgimg2 = loadImage("Screen 1/image.jpg");
bgimg3 = loadImage("Attack/attackButtonbg.jpg");
}
Simply use a css class with each images, and change on your command
(function ()
{
const bgClass = [ 'bg1', 'bg2', 'bg3' ]
, btChange = document.getElementById('bt-bg')
;
let noBg = 0;
document.body.className = bgClass[noBg];
btChange.onclick=_=>
{
noBg = ++noBg %3;
document.body.className = bgClass[noBg];
}
})();
body {
background-repeat: no-repeat;
background-attachment: fixed;
background-size: 100% 100%;
}
.bg1 { background-image: url(https://picsum.photos/id/251/500/300.jpg); }
.bg2 { background-image: url(https://picsum.photos/id/259/500/300.jpg); }
.bg3 { background-image: url(https://picsum.photos/id/254/500/300.jpg); }
<button id='bt-bg'> change </button>

Change h1 tag's color globally using javascript

I'm trying to implement a dark mode that activates according to the current time.
That's how I change the body's background color:
if (darkMode) {
document.body.style.backgroundColor = '#31403E';
} else {
document.body.style.backgroundColor = '#F2EDE4';
}
Can I change the h1 tag's color in some kind of global way? Or do I have to check for the property darkMode in every single doc and then assign the proper color.
In modern JavaScript, it could be:
const elements = document.querySelectorAll('h1')
Array.from(elements).forEach(el => el.style.color = '#31403E')
Hope this helps.
You can define a custom CSS stylesheet for dark mode:
#media (prefers-color-scheme: dark) {
color: white;
background: black
}
Where you can define your custom rules accordingly.
There's a nice trick about using filter as well that you can read a bit further over here
You can see this example over here:
https://codepen.io/rikschennink/pen/GLMLj
Where a class .dark-mode is set to the HTML document when toggling using
html.dark-mode {
filter: invert(100%);
img {
filter: invert(100%);
}
}
Docs
first of all they added dark mode preferences in css, they work like so:
#media (prefers-color-scheme: dark) {
h1 {
color: white;
}
}
but a common workaround to this back when we were developing theme switches was adding a "dark" class to the body and doing the following in css
body.dark h1 {
color: white;
}
IF YOU HAVE TO DO IT WITH JAVASCRIPT you have to loop through each and every h1's in the DOM, but it wont work on newly made h1s using javascript since it'll run on page load only as is.
let h1s = document.querySelectorAll("h1"); //gets all the h1s in the page
h1s.forEach( h1 => h1.style.color = "white");
With javascript you can do it like this:
var elements = document.getElementsByTagName("h1");
for(var i = 0; i < elements.length; i++) {
elements[i].style.color = "#000";
}

Is it possible to override an background image with another color?

I want to now if it is possible to override an background image with another color? In my case I want to create 4 checkboxes dynamically, and when these checkboxes are checked I want the color of the input field changed. I have tried to fix it by the code below, but it seems to not work.
Live Demo
Jquery:
var $div = $('<div />')
$('<input/>', {
"type": "text",
"class": "checkBoxCard"
}).appendTo($div);
$("#Getbtn").on("click", function () {
CheckBoxesChecked();
$('#modalDialog').dialog("close");
});
function CheckBoxesChecked() {
var numAll = $('input[type="checkbox"]').length;
var numChecked = $('input[type="checkbox"]:checked').length;
if (numChecked == numAll) {
$('.checkBoxCard').css("background-color", "yellow");
}
}
CSS:
.checkBoxCard {
background-image: url(http://static3.depositphotos.com/1004899/246/i/950/depositphotos_2465679-Cream-handmade-sheet-of-paper.jpg);
}
This will work for modern browsers, IE9+:
.checkBoxCard {
background: #eee url(img.png) 0 0 no-repeat;
}
.checkBoxCard:checked {
background-image: none;
background-color: yellow;
}

Categories