How to change background Image with DOM and JavaScript - javascript

Hi Everyone,
I am a beginner working on a small project in which I am facing an issue related to the background image (how I can change the background image using DOM and Javascript). I Have tried a few ways but am still on the problem side. I have used JavaScript function (random_image_picker(min,max)) for getting random image from Image_gallery. Everything going well until when I clicked on background_theme btn, the background image was supposed to be changed but not working. Every help would be appreciated.
Thanks
HTML Tag...
..Background Image....
<script>
const image_gallery = ['https://img.playbuzz.com/image/upload/ar_1.5,c_pad,f_jpg,b_auto/q_auto:good,f_auto,fl_lossy,w_480,c_limit,dpr_1/cdn/2c2dd0ea-8dec-4d49-8a95-f7b18f0b7aed/df312655-1d96-457d-88f4-cfc93c580d1d_560_420.jpg',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTwpR0X1hmpt4Kd2WviLXQGPrnUllW2UoLgtoWBoesgtFtSPFCF808bibJ8K2VhHRCki48&usqp=CAU',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRxmLTuD78jeZaVR3I_xfIuvmE4tse_JuhGjQ&usqp=CAU',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSxWrBodkwbTlxbMexeQCOneifPHaOUoTFwPA&usqp=CAU',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTtQMwmsMjdYfF0W0cyMPX673aKVK3m8sSDjg&usqp=CAU']
function random_image_picker(min, max) {
let a = Math.floor(Math.random() * (max - min + 1) + min);
return image_gallery[a];
}
let background_theme = document.querySelector('#background_theme');
let main = document.getElementsByTagName('main');
background_theme.addEventListener('click',function(){
main.style.backgroundImage = URL(random_image_picker(0,4))
})
</script>

BackgroundImage should be a string
The style.backgroundImage property accepts a string.
you can apply it using a template string `url(${random_image_picker(0, 4)})`
or using a regular concat like "url("+random_image_picker(0, 4)+")"
getElementsByTagName('main') return an array of elements
when you use getElementsByTagName you'll receive an array. If there's only 1 element to apply the background image to. you may select the first element using an 0 index.
document.getElementsByTagName('main')[0];
const image_gallery = ['https://img.playbuzz.com/image/upload/ar_1.5,c_pad,f_jpg,b_auto/q_auto:good,f_auto,fl_lossy,w_480,c_limit,dpr_1/cdn/2c2dd0ea-8dec-4d49-8a95-f7b18f0b7aed/df312655-1d96-457d-88f4-cfc93c580d1d_560_420.jpg',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTwpR0X1hmpt4Kd2WviLXQGPrnUllW2UoLgtoWBoesgtFtSPFCF808bibJ8K2VhHRCki48&usqp=CAU',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRxmLTuD78jeZaVR3I_xfIuvmE4tse_JuhGjQ&usqp=CAU',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSxWrBodkwbTlxbMexeQCOneifPHaOUoTFwPA&usqp=CAU',
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTtQMwmsMjdYfF0W0cyMPX673aKVK3m8sSDjg&usqp=CAU'
]
function random_image_picker(min, max) {
let a = Math.floor(Math.random() * (max - min + 1) + min);
return image_gallery[a];
}
let background_theme = document.querySelector('#background_theme');
let main = document.getElementsByTagName('main')[0];
background_theme.addEventListener('click', function() {
main.style.backgroundImage = `url(${random_image_picker(0, 4)})`
})
main {
width: 400px;
height: 400px;
border: 2px solid lime;
}
<main>
<button id="background_theme">swap theme</button>
</main>

Related

Strange flickering after manipulating html with JS

I am stuck with a problem and I cannot figure out what the cause is, I have created a small js script that modifies a table element, but every time it does I see flickering of the elements, I checked the HTML elements and there is no white space or whatsoever.
Short video: https://i.imgur.com/86RODJL.mp4
Is it possible an css property that causes this behavior ?
Tried to troubleshoot by inspecting the html elements for white space or similar.
JS function:
function correctOrderQtyMinus(element) {
var elementTR = element.parentNode.parentNode.parentNode;
var totalExBTW = document.getElementById('totalExBTW');
var totalBtw = document.getElementById('totalBtw');
var btwAmount = document.getElementById('btwAmount');
if(document.getElementById('checkoutForm')) {
if(element.parentNode.querySelector('#productQty').value > 1) {
var newAmount =+ parseFloat(elementTR.querySelector('#productPriceTotalBtw').innerText) - parseFloat(elementTR.querySelector('#productPriceWithBtw').innerText);
elementTR.querySelector('#productPriceTotalBtw').innerText =+ newAmount.toFixed(2);
totalExBTW.innerText =+ (parseFloat(totalExBTW.innerText)- parseFloat(elementTR.querySelector('#productPriceExBtw').innerText)).toFixed(2);
totalBtw.innerText =+ (parseFloat(totalBtw.innerText) - parseFloat(elementTR.querySelector('#productPriceWithBtw').innerText)).toFixed(2);
btwAmount.innerText = parseFloat(totalBtw.innerText - totalExBTW.innerText).toFixed(2);
totalBtw.innerText = parseFloat(totalBtw.innerText).toFixed(2);
totalExBTW.innerText = parseFloat(totalExBTW.innerText).toFixed(2);
elementTR.querySelector('#productPriceTotalBtw').innerText = parseFloat(elementTR.querySelector('#productPriceTotalBtw').innerText).toFixed(2);
} else {
console.log('Cannot go less than 1');
}
}
event.preventDefault();
}

adding scrolling images for a parallax background

I am trying to make multiple images (3) fade in and out as parallax background. I am currently using a large animated gif which is not going to cut it due to the loading times and what I eventually need. I am trying to target a "data-background" attribute which I have done but can't seem to get the images to change. I can get it to output in the console but not the data-background. Below is the code.
Thanks!
<section id="paralax-image" style="height: 400px;" class="module-cover parallax" data-background="" data-overlay="1"
data-gradient="1">
(function () {
// The images array.
var images = ["assets2/Arcadian.jpg", "assets2/AngryPrawns.jpg", "assets2/Apricot_Smash.jpg"];
// The counter function using a closure.
var add = (function() {
// Setting the counter to the last image so it will start with the first image in the array.
var counter = images.length - 1;
return function() {
// When the last image is shown reset the counter else increment the counter.
if(counter === images.length - 1) {
counter = 0;
} else {
counter+=1;
}
return counter;
}
})();
// The function for changing the images.
setInterval(
function() {
var section = document.getElementById("paralax-image");
section.getAttribute("data-background");
section.setAttribute('data-background', images[add()]);
console.log(images[add()]);
}
, 3000);
})();
First of all, attributes that have "data-" in front of them are only used to store some custom data on elements. Those attributes do not influence the appearance/behaviour of your app in any way unless you use them in your JS/CSS.
So, in your code, you are setting the data-background attribute on your section. The code is working correctly and if you look into the inspector, you can actually see that that attribute's value is changing as expected.
The next step for you would be to display the images that you set in your data-background attribute - either using JS or CSS.
Unfortunately, for now, it's not possible to grab the background URL from attribute value in CSS as described in the top-voted answer here: Using HTML data-attribute to set CSS background-image url
However, you can still manually set the CSS background-image property using JavaScript based on the "data-" property.
// The images array.
const images = ["https://images.pexels.com/photos/255379/pexels-photo-255379.jpeg?auto=compress&cs=tinysrgb&h=350", "https://images.pexels.com/photos/531880/pexels-photo-531880.jpeg?auto=compress&cs=tinysrgb&h=350", "https://images.unsplash.com/photo-1530482817083-29ae4b92ff15?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=44f4aebbd1e1371d5bf7dc22016c5d29&w=1000&q=80"];
const imagesSwitcher = () => {
const getCounter = () => {
// Setting the counter to the last image so it will start with the first image in the array.
let counter = images.length - 1;
return () => {
// When the last image is shown reset the counter else increment the counter.
if(counter === images.length - 1) {
counter = 0;
} else {
counter += 1;
}
return counter;
}
}
const counter = getCounter();
const updateBackground = () => {
const section = document.getElementById("paralax-image");
section.style.background = `url(${images[counter()]}) no-repeat`;
};
updateBackground();
setInterval(() => updateBackground(), 3000);
};
imagesSwitcher();
.dynamic-background {
display: block;
width: 500px;
height: 200px;
background-size: 100%;
}
<div>
<section id="paralax-image" class="dynamic-background" style="height: 400px;" class="module-cover parallax" data-background="" data-overlay="1" data-gradient="1">
</section>
</div>
The thing is - in this case, you don't even actually need this data-background property. You can simply switch background image using JS.
Now, it's not very clear what you meant by parallax in your case. In case you actually meant parallax background like in here http://jsfiddle.net/Birdlaw/ny8rqzu5/, you would need to take a different approach overall. Please comment if you need any help with this.

Dynamic progress bar based on progress of script?

I have a Google App Engine application, using the webapp2 framework, that interacts with a MySQL database. Users of the application can upload data. During uploading, I want to show a progress bar, since it can take up to some minutes.
Based on what I've seen in other topics (mainly: this topic and this one), I'm working on a JSON/Javascript solution, which are both new to me.
The progress bar itself is working if I'm passing a random number. However, I can't figure out how to 'load' the changing values from the Python script.
Here's the HTML/CSS/Javascript:
HTML:
<div id="myProgress">
<div id="myBar"</div>
</div>
CSS:
#myProgress {width: 300px;
height: 30px;
background-color: #ddd;
}
#myBar {width: 1%;
height: 30px;
background-color: #4CAF50;
}
Javascript:
<script type="text/javascript">
function move() {
var elem = document.getElementById("myBar");
var width = 1;
var id = setInterval(frame, 1000);
function frame() {
if (width >= 100) {
clearInterval(id);
}
else {
//var randomnumber = Math.floor(Math.random() * 100); --> works
var randomnumber = function update_values() {
$SCRIPT_ROOT = {{ script_root }};
$.getJSON($SCRIPT_ROOT+"/uploading",
function(data) {
$("#width").text(data.width+" %")
});
} ; --> this is wrong I assume
var width = randomnumber;
elem.style.width = width + '%';
}
}
}
window.onload=move();
</script>
The progress comes from a for loop in Python which is embedded in the script that loads the page. After the script is finished with one activity, I want the result of counter to be passed to the progress bar as its width. With static variables, I use the regular Jinja way.
class UploadingpageHandler(webapp2.RequestHandler):
def get(self):
activities_list = [1,2,3,4,5,6,7,8,9,10]
counter = 0
script_root = 'localhost:10080'
for activity in activities_list:
counter = counter + 10
upload.do_stuff_in_some_function_with_MySQL()
obj = {
'width': counter
}
self.response.headers['Content-Type'] = 'application/json' --> this
self.response.out.write(json.dumps(obj)) --> and this is wrong I assume
template_vars = {
'script_root': script_root
}
template = jinja_environment.get_template('uploading.html')
self.response.out.write(template.render(template_vars))
How to alter the scripts to get it working? Or is there a better way to solve this?
You need to store the progress of your "activities" outside of your function somewhere.
A hacky "solution" would be to store it into some sort of caching solution like memcached or redis with some sort of timestamp/signature so that you can retrieve it (and invalidate the old entries with a cron job-type thing).
Or you could go balls out and make your task entirely async with something like Celery, but I doubt you can do that on Google App Engine.

Random Image refreshed after set time

so earlier I asked about creating a javascript which automatically picks an image out of the a directory randomly.
The script works perfectly, however. I would like to modify the script so that it picks an image at random to load (which it already does) then, after a set time like 10 seconds, will fade out and a new randomly picked image will fade in.
Here is the existing code:
function randomImage() {
var fileNames = [
"1.jpg",
"2.jpg",
"3.jpg"
];
var randomIndex = Math.floor(Math.random() * fileNames.length);
document.getElementById("background").background = "backgrounds/" + fileNames[randomIndex];
}
Thank you!
You can call your function after regular intervals like this. First call is to set image for the first time. If you are already using it, ignore it.
randomImage();
setInterval(randomImage,10000);
Here you go it's just like before only I added setTimeout()
pass an anonymous function which calls the randomImage() function every 10 seconds, 10000 ms.
function randomImage() {
var fileNames = [
"1.jpg",
"2.jpg",
"3.jpg"
];
var randomIndex = Math.floor(Math.random() * fileNames.length);
document.getElementById("background").background = "backgrounds/" + fileNames[randomIndex];
setTimeout(function() {
randomImage();
}, 10000);
}
Use DOMElement.style.background instead of DOMElement.background to set the background of the HTML element.
To execute certain function or expression after specific duration, use Window setInterval(). It accepts 2 arguments. First argument is Callback function and second argument is the interval.
Note: This example will change the background style of element. It will not give you fadeIn/fadeOut animation.
Try this:
function randomImage() {
var fileNames = [
"http://ryanlb.com/images/other/images/getter-dragon-1.jpg",
"http://ryanlb.com/images/other/images/getter-dragon-2.jpg"
];
var randomIndex = Math.floor(Math.random() * fileNames.length);
document.getElementById("background").style.background = 'url(' + fileNames[randomIndex] + ')';
}
randomImage();
setInterval(randomImage, 10000);
* {
padding: 0;
margin: 0;
}
html,
body {
width: 100%;
height: 100%;
}
#background {
width: 100%;
height: 100%;
background-size: 100% auto;
}
<div id="background"></div>
Fiddle here
you want to set element background url so its need like
document.getElementById("background").style.background = "url('backgrounds/" + fileNames[randomIndex]+"')";
if you want to set image url ,
document.getElementById("background").src= "backgrounds/" + fileNames[randomIndex];

Adding random class to the div

At the moment in my game, when it is complete a random image is passed to the "reveal-wrapper" to display at the end.
I still want to do this but instead of doing it this way I would like to add a random class each time to the "revael-wrapper" to make it ".reveal-wrapper .image1" for example. There will be 5 different images and I want it to pick one at random each time.
The code for it at the moment is as follows:
$(document).ready(function () {
bgImageTotal = 5;
randomNumber = Math.round(Math.random() * (bgImageTotal - 1)) + 1;
imgPath = ('images/reward-images/' + randomNumber + '.png');
$('.reveal-wrapper').css('background-image', ('url("' + imgPath + '")'));
});
Any ideas how I would add a random class instead?
You've already got the logic in place, you just need to add the class. Try this:
$(document).ready(function () {
bgImageTotal = 5;
randomNumber = Math.round(Math.random() * (bgImageTotal - 1)) + 1;
$('.reveal-wrapper').addClass('image' + randomNumber);
});
All you then need to do is setup the classes in your CSS:
.image1 { background-image: url('images/reward-images/1.png'); }
.image2 { background-image: url('images/reward-images/2.png'); }
.image3 { background-image: url('images/reward-images/3.png'); }
.image4 { background-image: url('images/reward-images/4.png'); }
.image5 { background-image: url('images/reward-images/5.png'); }
Since you already have the random numbers, and provided your images have the same filename structure (image1, image2, ect.)
$('.reveal-wrapper').addClass('image' + randomNumber);
Rory has a fine solution, but if you're so curious here's something a little more general:
function add_rand_class (classes, elem) {
$(elem).addClass(classes[Math.random() * classes.length >> 0]);
}
pass the function an array of class strings and the element on which you want the class, and you're good to go.

Categories