I am using JavaScript to randomly change the background image upon refresh. What I have been wanting to do is then take the current background-image url and paste it in a certain div within
so that people can download the image.
The background image script works and is as follows:
var totalCount = 3;
function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'bgimages/'+num+'.jpg';
document.body.style.backgroundRepeat = "repeat";// Background repeat
}
Sorry if this is easy but I haven't been able to figure out how to do it! Can anyone point me in the right direction?
Let's assume you have this link somewhere in your document and you want it to point to the current background image:
<a href='#' id='bgDownload'>Download background image</a>
The following function changes now the "href"-attribute of the link to the current background and the background itself:
var totalCount = 3;
function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'bgimages/'+num+'.jpg';
document.body.style.backgroundRepeat = "repeat";// Background repeat
// change link
document.getElementById("bgDownload").href = 'bgimages/'+num+'.jpg';
}
I hope it helps...
Put a DIV on your page in the HTML, and switch the content using...
document.getElementById("[ID of DIV]").innerHTML = '' + [text_var] + '';
Something like this...
document.getElementById("[ID of DIV]").innerHTML = 'Image #' + num + '';
Try this
<a href='javascript:window.location.href=document.body.background'>
Download Background
</a>
try this :
function downloadImage{
window.open(document.body.background,'_blank');
}
Related
I need to make the background image in div tag and it has to change automatically, I already put the array of images inside the javascript, but the images is not showing when i'm run the site.The background should behind the menu header.
This is the div
<div style="min-height:1000px;position:relative;" id="home">
below of the div is containing the logo, menu and nav part.
<div class="container">
<div class="fixed-header">
<!--logo-->
<div class="logo" >
<a href="index.html">
<img src="images/logo.png" alt="logo mazmida" height="142" width="242">
</a>
</div>
<!--//logo-->
This is the javascript
<script>
var imgArray = [
'images/1.jpg',
'images/2.jpg',
'images/3.jpg'],
curIndex = 0;
imgDuration = 2000;
function slideShow() {
document.getElementID('home').src = imgArray[curIndex];
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout("slideShow()", imgDuration);
}
slideShow();
You have a few issues with your script. I've made a live JSbin example here:
https://jsbin.com/welifusomi/edit?html,output
<script>
var imgArray = [
'https://upload.wikimedia.org/wikipedia/en/thumb/0/02/Homer_Simpson_2006.png/220px-Homer_Simpson_2006.png',
'https://upload.wikimedia.org/wikipedia/en/thumb/0/0b/Marge_Simpson.png/220px-Marge_Simpson.png',
'https://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png'
];
var curIndex = 0;
var imgDuration = 1000;
var el = document.getElementById('home');
function slideShow() {
el.style.backgroundImage = 'url(' + imgArray[curIndex % 3] + ')';
curIndex++;
setTimeout("slideShow()", imgDuration);
}
slideShow();
</script>
There are a few issues with your script:
On the element since it's a div not an img, you need to set style.backgroundImage instead of src. Look at https://developer.mozilla.org/en-US/docs/Web/CSS/background for other attributes to related to background image CSS
Also it's document.getElementById
Optimizations
And you can use mod % trick to avoid zero reset
Use setInterval instead of setTimeout
Further optimzations
Use requestAnimationFrame instead of setTimeout/setInterval
I suggest getting familiar with your browser debugging tools which would help identify many of the issues you face.
document.getElementID('home').src = imgArray[curIndex]
You are targeting a div with an ID of home, but this is not an Image element (ie ,
But since you want to alter the background colour of the DIV, then you use querySelector using javascript and store it in a variable, then you can target the background property of this div (ie Background colour).
I hope this helps.
You are trying to change the src property of a div, but divs do not have such property.
Try this:
document.getElementById('home').style.backgroundImage = "url('" + imgArray[curIndex] + "')"
This changes the style of the target div, more precisely the image to be used as background.
As you want to change the background image of the div, instead of document.getElementID('home').src = imgArray[curIndex] use
document.getElementById("#home").style.backgroundImage = "url('imageArray[curIndex]')";
in JavaScript or
$('#home').css('background-image', 'url("' + imageArray[curIndex] + '")'); in jquery.
To achieve expected result, use below option of using setInterval
Please correct below syntax errors
document.getElementID to document.getElementById
.src attribute is not available on div tags
Create img element and add src to it
Finally use setInterval instead of setTimeout outside slideShow function
var imgArray = [
'http://www.w3schools.com/w3css/img_avatar3.png',
'https://tse2.mm.bing.net/th?id=OIP.ySEgAgJIlDQsIQTu_MeoLwHaHa&pid=15.1&P=0&w=300&h=300',
'https://tse4.mm.bing.net/th?id=OIP.wBAPnR04OfXaHuFI9Ny2bgHaE8&pid=15.1&P=0&w=243&h=163'],
curIndex = 0;
imgDuration = 2000;
var home = document.getElementById('home')
var image = document.createElement('img')
function slideShow() {
if(curIndex != imgArray.length-1) {
image.src = imgArray[curIndex];
home.appendChild(image)
curIndex++;
}else{
curIndex = 0;
}
}
setInterval(slideShow,2000)
<div style="position:relative;" id="home"></div>
code sample - https://codepen.io/nagasai/pen/JLKvME
Lets say I have these images gallery, how do i randomly display the images everytime when i reload the page?
http://creativepreviews.com/fiddle/study/20131007/
Let's say the image will display in the background of the DIV, then the following should do it.
// JS
var imgArray = ["img1.jpg", "cat.jpg", "sky.jpg"]
function randomBg() {
x = Math.random()
y = Math.round(x * 10)
if (imgArray[y] != undefined) {
document.getElementById("blah").style.backgroundImage = "url('" + imgArray[y] + "')"
} else {
document.getElementById("blah").style.backgroundImage = "url('default.jpg')"
}
}
...and the HTML.
<script src="test.js"></script>
<body onload="randomBg()">
<div id="blah"></div>
...or you could replace the style.backgroundImage in the JS with innerHTML = <img src=" etc...
You could do something along these lines (not tested)
var grd = $('#grid');
var imgs = grd.children();
imgs.sort(function(){return (Math.round(Math.random()) - 0.5);});
grd.remove('li');
for(var i=0;i < imgs.length;i++) grd.append(imgs[i]);
In essence what we are doing is getting all the li elements in 'grid' into an array, randomizing them, removing them all from 'grid' and then putting them back in again.
If you had supplied a working fiddle rather than a link to the finished article it would be easier to modify it and provide a more complete solution.
I'm not knowledgeable in JS and Jquery so I'm really hoping someone here could help me out.
I want my banner to change image on page load or refresh and I found this code:
<script type="text/javascript">
window.onload = function () {
var random = document.getElementById('random');
var pictures = new Array('images/icn_slide-1.jpg','images/icn_slide-2.jpg','images/icn_slide-1.jpg','images/icn_slide-2.jpg');
var numPics = pictures.length;
if (document.images) {
var chosenPic = Math.floor((Math.random() * numPics));
random.style.background = 'url(' + pictures[chosenPic] + ')';
}
}
The script above works pretty well(background image changes every refresh) but now I want to add a previous and next button(actually I already did) so that when viewers click on next/previous it would display another image. Is there a simple way to do this? How do I make my next and previous button work? Any help would be greatly appreciated. Thanks!
This is the only content inside the of my html:
<div id="random" style="width: 1399px; height:515px; margin:auto;">
<div id="slide_control" class="clearfix">
<span id="prev"><img alt="" title="" src="images/icn_nav-arrow2.png" /></span>
<span id="next"><img alt="" title="" src="images/icn_nav-arrow.png" /></span>
</div>
</div>
It's the #random div that changes background image on refresh as of now and I want it just like that. I added the "slide_control" which contained the "prev" and "next" button and what I want them to do is to also change the background-image of #random when they're clicked.
Most JS/JQquery slider and plugins comes with buttons and controllers but they auto-play images and if I disable the autoplay, they don't change banner/background on refresh.
I only want the images/background to randomly change on refresh or change when prev/next buttons are clicked but I don't know how to achieve this.
Here's a basic example of what you are asking for:
<script type="text/javascript">
function rotateImage(idx) {
var random = document.getElementById('random');
if (document.images) {
random.style.background = 'url(' + pictures[idx] + ')';
selectedImage = idx;
}
}
function getNext() {
var nextImage = selectedImage + 1;
if (selectedImage >= numPics) {
nextImage = 0;
}
rotateImage(nextImage);
}
function getPrev() {
var prevImage = selectedImage - 1;
if (selectedImage < 0) {
selectedImage = numPics -1;
}
rotateImage(prevImage);
}
var pictures = new Array('images/icn_slide-1.jpg','images/icn_slide-2.jpg','images/icn_slide-1.jpg','images/icn_slide-2.jpg');
var numPics = pictures.length;
var selectedImage = null;
window.onload = function () {
var chosenPic = Math.floor((Math.random() * numPics));
rotateImage(chosenPic);
document.getElementById('next').onclick = getNext;
document.getElementById('prev').onclick = getPrev;
}
</script>
I am a js newbie. I Have looked for answers to this particular issue but have not found an answer yet in this forum or others, so sorry if it's here and I missed it. I have a script that works for loading a random image from an array to an id element placed directly in the html when the page loads.
I'm trying to see if I can get it to do the same thing but do it for a background image in a id element in a css file. I have firebug and it doesn't give me any error messages with this but it doesn't work either.
window. onload = choosePic;
var myPix = new
Array("images/image1.gif", "images/image2.gif");
function choosePic() {
randomNum = Math.floor((Math.random() * myPix.length));
document.getElementById("headerAnimation").style.backgroundImage.src = myPix[randomNum];
}
You have it almost right.
window.onload = choosePic;
var myPix = new Array("images/image1.gif", "images/image2.gif");
function choosePic() {
var randomNum = Math.floor((Math.random() * myPix.length));
document.getElementById("headerAnimation").style.backgroundImage =
"url(" + myPix[randomNum] + ")";
}
I know this question has been asked before, but if someone could explain in greater detail it would be awesome. I have a div and a table and an image inside this div. I am making a image gallery, so I have two links forward and back, how do I make these links change the image, or rather all the content inside the div. I am very new to javascript, actually I know nothing at all about it, if I could get a step by step instruction that would be awesome, I have tried so of the other post codes but can not get it to work, so I have no idea what I am doing wrong.
Sample HTML:
<html>
<head><title>Dummy page</title></head>
<body>
<div id="divID">
<img id="backImg" src="http://test.com/sample.jpg">
</div>
</body>
</html>
To change the whole div:
var div = document.getElementByID('divID');
div.innerHTML = "<b>This is some html</b>";
To just change the image:
var img = document.getElementByID('backImg');
img.src = "http://www.host.com/image.jpg';
Here's a good example that I made that might help. Try it out -- http://jsfiddle.net/SuperBoi45/XMSGe/
Here's the code for a quick look:
HTML:
<button id="before">Previous</button>
<button id="next">Next</button>
<div id="imageGallery"></div>
JavaScript:
function $(id) {
return document.getElementById(id);
}
var foward = null,
back = null,
images = [
"http://www.toxel.com/wp-content/uploads/2009/04/conceptcar04.jpg",
"http://politicolnews.com/wp-content/uploads/2010/01/bill-gates-car.jpg",
"http://www.youthedesigner.com/wp-content/uploads/2008/05/car-wallpapers19.jpg",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-555c9ae9cfd364db5307b2e8d717a00d",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-01589fb639efec5433a3e30a8a8dd449",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-31f8cbd6627edc1ba9ef2828f3423fdf",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-0f47a0c2db85b5d7c134d41bcdc65b2e",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-739fd589778207e542a6e31873a24433",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-6056a5df58462ea4951a2b328243b7a2",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-59028363fc0f7d0ee7aa1ebc5e72713a",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-eb09864be7a1fbe7e821bc1ee08c3a8b",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-50bd88090e05a452bba67d510ba4a0cc",
"http://d2o7bfz2il9cb7.cloudfront.net/main-qimg-191b37eea296e90a242d24db90824c5c"
];
var img = new Image();
for (var i = 0; i < images.length; i++) { // caching the images for performance boost
img.src = images[i];
}
var image = {
count: -1,
next: function() {
if (image.count == (images.length) - 1) return false;
image.count += 1;
$('imageGallery').innerHTML = "<img src=\"" + images[image.count] + "\"\/>";
},
previous: function() {
if (image.count <= 0) return false;
image.count -= 1;
$('imageGallery').innerHTML = "<img src=\"" + images[image.count] + "\"\/>";
}
};
foward = image.next;
back = image.previous;
$('next').addEventListener("click", foward);
$('before').addEventListener("click", back);
The best thing about this is that all you have to do is add a new image URL to the array and it will still work.
If you want to change the images but not all the content in the div, I'd recommend putting in another div outside the image gallery.