how to change the image when a page is refreshed using JavaScript? - javascript

I want to change the image when the page is refresh using html. I place my partial code here. i want a script or anything do change the image when the page gets refresh.. Please help me to do this using html ...
<div class="one-image">
<a href="">
<img src="img/IMG_1035.jpg" class="giThumbnail" alt="Nightclubs"></a><h4 class="giDescription">
Nightclubs</h4>
</div>
the above image tag image is change every refresh.. please help me ..

I believe this would work, but all your images would have to be sequentially named, e.g. 1-100. Also note that the script was placed AFTER the IMG tag.
<div class="one-image">
<a href="">
<img id="imgRand" src="" class="giThumbnail" alt="Nightclubs">
</a>
<h4 class="giDescription">
Nightclubs
</h4>
</div>
<script language="javascript">
// random number between 1 and 100
var numRand = Math.floor(Math.random()*101);
document.getElementById("imgRand").src = "img/IMG_"+numRand+".jpg";
</script>
The random formula in JS is:
var random = Math.floor(Math.random() * (max - min + 1)) + min;
so if you only had 5 images between 135 and 140 your script would look like:
var random = Math.floor(Math.random() * (140 - 135 + 1)) + 135;
If you wanted to change the image client-side, like a slideshow, just add a timer.
<script language="javascript">
function setImg(){
// random number between 1 and 100
var numRand = Math.floor(Math.random()*101);
document.getElementById("imgRand").src = "img/IMG_"+numRand+".jpg";}
// call it the first time
setImg();
// set an interval to change it every 30 seconds
window.setInterval("setImg()",30000);
</script>

Not Tested but something like this should work using Javascript:
//Add following inside script tag
//Add id to your image tag
var theImages = new Array();
theImages[0] = 'images/first.gif' // replace with names of images
theImages[1] = 'images/second.gif' // replace with names of images
theImages[2] = 'images/third.gif' // replace with names of images
......
var j = 0
var p = theImages.length;
var preBuffer = new Array();
for (i = 0; i < p; i++){
preBuffer[i] = new Image();
preBuffer[i].src = theImages[i];
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.getElementById("yourImgTagId").src = theImages[whichImage];
}
//call the function
showImage();
Did you mean something like that

What type of server are you using? Using PHP or ASP you can accomplish this using a script that cycles through your images in a script. So your HTML would just point to the script instead of directly to an image:
<img src="image_rotation_script.php" class="giThumbnail" alt="Nightclubs">
Then your script would rotate through your various images. Here is a PHP example:
<?php
header('content-type: image/jpeg');
// Your own logic here to pull from a database, randomize an array of images etc.
$images = array('img/IMG_1.jpg','img/IMG_2.jpg','img/IMG_3.jpg');
$imageFile = array_rand($images);
$image = imagecreatefromjpeg($imageFile);
imagejpeg($image);
imagedestroy($image);
?>

Use can use JavaScript to change the src field of the image tag. First insert an ID attribute to your img tag, or a NAME attribute if it appears more often on the same page.
<img id="nightClubImage" src="img/IMG_1035.jpg" class="giThumbnail" alt="Nightclubs">
Then write a script and change the src field:
document.getElementById('nightClubImage').src = "newImage.jpg";

If you want use only client-side solution try this:
<img src="img/IMG_1035.jpg" class="giThumbnail" alt="Nightclubs">
<script type="text/javascript">
var images = ['img/IMG_1035.jpg', 'img/IMG_1036.jpg', 'img/IMG_1037.jpg'];
document.getElementById('gitThumbnail').src = images[Math.round((Math.random() * (images.length-1))];
</script>

Related

Pass Javascript variable to URL

I have a bunch of URL's that automatically load images on a webpage I am developing:
<a href="https://www.sample1.com" target="_blank">
<img src="https://www.sample1.com" alt="sample1"
<a href="https://www.sample2.com" target="_blank">
<img src="https://www.sample2.com" alt="sample2">
...
However, some of the images that I need displayed are dynamic and are based on the current time. I know how to get the proper time, hour, and hour in UTC, and then properly define the variable:
<script type="text/javascript">
var datee = new Date()
var yyyy = datee.getFullYear()
var mm = datee.getMonth() + 1
var dd = datee.getDate()
var mms = datee.getMinutes()
var hh_UTC = datee.getUTCHours()
var outlook_hour = []
if (parseInt(hh_UTC) > 0 && parseInt(hh_UTC) < 12){outlook_hour = "0100"}
if (parseInt(hh_UTC) > 11 && parseInt(hh_UTC) < 13){outlook_hour = "1200"}
if (parseInt(hh_UTC) > 13 && parseInt(hh_UTC) < 17){outlook_hour = "1630"}
if (parseInt(hh_UTC) > 16 && parseInt(hh_UTC) < 21){outlook_hour = "2000"}
var url1 = "https://sample_img_" + outlook_hour + ".gif"
</script>
How am I able to extract the 'url1' variable to have the image load on my page in similar fashion to the first block of code provided? All I could find while searching online is the 'document.getElementbyID' in which I don't really have an 'ID'. Therefore, something along the lines of:
<a href="https://www.updated_img.com" target="_blank">
<img src=document.getElementbyID(url1) alt="sample_img">
would not work. Therefore, how would I be able to pass the 'url1' variable in the above piece of code to work?
You'll need to give your image an id, and then set the src attribute of it to the value of the variable:
HTML:
<a href="https://www.updated_img.com" target="_blank">
<img id="image1" alt="sample_img">
JavaScript:
window.addEventListener("load", () => {// wait until the page is fully loaded before interacting with the document
document.getElementById("image1").setAttribute("src", url1);
})

Changing link suffix with javascript on keypress

I'm new to Javascript, so bear with me. Let's say I have this link: example.com/img/000.png/. It displays an image source, so I'll put it in an image tag. <img src="example.com/img/001.png/">.
When I press a key (right arrow, for example), the link should change (inside the image tag) to example.com/img/001.png/, /002.png/, /003.png/, etc. is is possible, at all, to do this with Javascript, embedded in the raw HTML?
Here are my thoughts so far:
<img src=" <!-- Link generated by Javascript --> ">
<script>
// actually pythonic pseudocode, ok
counter = 0
if (right arrow key pressed):
counter = counter + 1
counterPrep = (3-len(counter))*'0'+str(counter)
// ^^^ changes the link from "1" to "001"
link = "https://www.example.com/img/"+str(counterPrep)+".png
</script>
I know what I'm asking may be unclear, so feel free to ask questions. I usually work in Python, which is why the pseudocode is so "Pythonic".
Thanks!
You can detect the key press of the user using the event called keypress.
The rigth arrow key has a key code 39, so you can do the following :
<img src="example.com/img/001.png" id="myImage">
<script>
var counter = 0;
document.body.addEventListener("keypress", function(e){
if(e.keyCode==39) {
counter ++;
var index = (("00" + counter).slice(-3));
var link = "https://www.example.com/img/"+index+".png";
document.getElementById('myImage').src = link;
}
});
</script>
Please see the snippet below:
document.getElementById("testBtn").onclick = function() {
var imgSrc = document.getElementById("dynamicImg").src;
var start = imgSrc.lastIndexOf("/") + 1, end = imgSrc.lastIndexOf("/") + 4;
var preUrl = imgSrc.substring(0, start);
var postUrl = imgSrc.substring(end, imgSrc.length);
// get the fileName
var imgName = parseInt(imgSrc.substring(start, end)) + 1;
// convert to 000 format
imgName = ("00" + imgName).slice(-3);
// replace img src
document.getElementById("dynamicImg").src = preUrl + imgName + postUrl;
alert(document.getElementById("dynamicImg").src)
};
<img id="dynamicImg" src="example.com/img/000.png" />
<button id="testBtn">
TEST
</button>
The code above will work using dynamic url.
I tried it using onclick button, but you can change the event ti keypress.
I hope this helps.

Simple JavaScript formatting

Sorry to be such a noob, but I've looked for this answer and can't find anything relevant.
Im trying to add some javascriptcode to a squarespace website. The code is to display a random image.
I have to format the code and insert links to where my images are hosted but I'm not sure what to format
This is the bare code:
<script language="JavaScript">
<!--
/*
Random Image Script- By JavaScript Kit (http://www.javascriptkit.com)
Over 400+ free JavaScripts here!
Keep this notice intact please
*/
function random_imglink() {
var myimages = new Array()
//specify random images below. You can have as many as you wish
myimages[1] = "image1.gif"
myimages[2] = "image2.gif"
myimages[3] = "image3.gif"
myimages[4] = "image4.gif"
myimages[5] = "image5.gif"
myimages[6] = "image6.gif"
var ry = Math.floor(Math.random() * myimages.length)
if (ry == 0)
ry = 1
document.write('<img src="' + myimages[ry] + '" border=0>')
}
random_imglink()
//-->
</script>
<p align="center">This free script provided by<br />
JavaScript Kit
</p>
And this is the links I've added? have i edited it correctly?
<script language="JavaScript">
<!--
/*
Random Image Script- By JavaScript Kit (http://www.javascriptkit.com)
Over 400+ free JavaScripts here!
Keep this notice intact please
*/
function random_imglink() {
var symimages = new Array()
//specify random images below. You can have as many as you wish
symimages[1] = "1.jpg"
symimages[2] = "2.jpg"
symimages[3] = "3.jpg"
symimages[4] = "4.jpg"
symimages[5] = "5.jpg"
var ry = Math.floor(Math.random() * symimages.length)
if (ry == 0)
ry = 1
document.write('<img src="http://www.mattselley.com/symimages'+symimages[ry]+'" border=0>')
}
random_imglink()
//-->
</script>
<p align="center">This free script provided by<br />
JavaScript Kit
</p>
When I add that code to the squarespace site, in code injection, it doest work, so I'm missing something here, and i think i haven't got the links correct - this is supposed to be a cut and paste code, so I'm doing something wrong.
Any help would be great.
Thanks in advance.
<scripe language="JavaScript">
var imgs = ['http://lorempizza.com/380/240',
'http://dummyimage.com/250/ffffff/000000',
'http://lorempixel.com/g/400/200/',
'http://lorempixel.com/g/400/200/sports/'];
var container = document.getElementById('imageContainer');
var ry = Math.floor(Math.random() * imgs.length)
if (ry == 0)
ry = 1
var img = document.createElement('img');
img.src = imgs[ry]; // img[i] refers to the current URL.
container.appendChild(img);
</script>
<div id="imageContainer"> </div>
This is what you want. Just replace my that urls with yours.
OR if you want to go with your approach..make correction as ..
document.write('<img src="http://www.mattselley.com/symimages/'+symimages[ry]+'" border=0>')
add / at then end of src.
Dont forget to Tick and Upvote ;)

Pass variables to code <input type="image" src="imageSrc;" >

hope someone can help a noob. Many thanks in advance.
I have an index page with links to hundreds of other pages holding song words.
I have built each song page but it would be MUCH simpler to have one MASTER page that took a variable from the index page and found the corresponding words (which exist as png graphics.)
I have sorted Step 1 - I can pass a variable from the index page to the master page using:
<a href="javascript: window.open('MUSIC/beatles/mastertest2.html?song=ER', '_parent')">
where song=ER is the variable to display the words for Eleanor Rigby. For Step 2, I can also retrieve that information in the master page with:
var imageSrc = (qs("song")+".png"); document.write(imageSrc);
which will display the text ER.png which is the name of the image I want to display.
For Step 3 I am trying to get this same variable read into:
<input type="image" src="imageSrc;">
to display the picture. I have searched this and other forums for days now and nothing suggested works for me. I could be missing out an essential early step in the coding?
Update:
My master html file has this code to retrieve the variable:
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
And it uses this code to disply the variable (appended with .png) just to prove to me that it is getting through:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
Then I am trying to feed the variable into a routine to display the png selected. The next script doesn't work but I am thrashing about trying anything right now:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
<input type="image" src="#imageSrc;" border="0" value="Notes" onClick="placeIt(); showIt()">
<input id="song-image" type="image">
var imageSrc = 'ER.png';
var input = document.getElementById('song-image');
input.src = imageSrc;
If you have already <input type="image"> in your HTML page, you must add an id and then set it's src attribute with
HTML:
<input id="song-image" type="image">
JS:
var imageSrc = 'http://www.lorempixel.com/200/100';
var input = document.getElementById('song-image');
input.src = imageSrc;
JSFiddle for testing.
If I understood you right, its very simple. Are you looking for this?
var input = document.createElement('input');
input.type = 'image';
input.src = imageSrc;
document.body.appendChild(input);
If you can print the variable imageSrc using document.write, then you can use it like shown above.

Get Image Source URLs from a Different Page Using JS

Everyone:
I'm trying to grab the source URLs of images from one page and use them in some JavaScript in another page. I know how to pull in images using JQuery .load(). However, rather than load all the images and display them on the page, I want to just grab the source URLs so I can use them in a JS array.
Page 1 is just a page with images:
<html>
<head>
</head>
<body>
<img id="image0" src="image0.jpg" />
<img id="image1" src="image1.jpg" />
<img id="image2" src="image2.jpg" />
<img id="image3" src="image3.jpg" />
</body>
</html>
Page 2 contains my JS. (Please note that the end goal is to load images into an array, randomize them, and using cookies, show a new image on page load every 10 seconds. All this is working. However, rather than hard code the image paths into my javascript as shown below, I'd prefer to take the paths from Page 1 based on their IDs. This way, the images won't always need to be titled "image1.jpg," etc.)
<script type = "text/javascript">
var days = 730;
var rotator = new Object();
var currentTime = new Date();
var currentMilli = currentTime.getTime();
var images = [], index = 0;
images[0] = "image0.jpg";
images[1] = "image1.jpg";
images[2] = "image2.jpg";
images[3] = "image3.jpg";
rotator.getCookie = function(Name) {
var re = new RegExp(Name+"=[^;]+", "i");
if (document.cookie.match(re))
return document.cookie.match(re)[0].split("=")[1];
return'';
}
rotator.setCookie = function(name, value, days) {
var expireDate = new Date();
var expstring = expireDate.setDate(expireDate.getDate()+parseInt(days));
document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/";
}
rotator.randomize = function() {
index = Math.floor(Math.random() * images.length);
randomImageSrc = images[index];
}
rotator.check = function() {
if (rotator.getCookie("randomImage") == "") {
rotator.randomize();
document.write("<img src=" + randomImageSrc + ">");
rotator.setCookie("randomImage", randomImageSrc, days);
rotator.setCookie("timeClock", currentMilli, days);
}
else {
var writtenTime = parseInt(rotator.getCookie("timeClock"),10);
if ( currentMilli > writtenTime + 10000 ) {
rotator.randomize();
var writtenImage = rotator.getCookie("randomImage")
while ( randomImageSrc == writtenImage ) {
rotator.randomize();
}
document.write("<img src=" + randomImageSrc + ">");
rotator.setCookie("randomImage", randomImageSrc, days);
rotator.setCookie("timeClock", currentMilli, days);
}
else {
var writtenImage = rotator.getCookie("randomImage")
document.write("<img src=" + writtenImage + ">");
}
}
}
rotator.check()
</script>
Can anyone point me in the right direction? My hunch is to use JQuery .get(), but I've been unsuccessful so far.
Please let me know if I can clarify!
Try this.
<script>
$.get('http://path/to/page/1', function(data) {
var imgs = $('<div/>').html(data).find('img');
imgs.each(function(i, img) {
alert(img.src); // show a dialog containing the url of image
});
});
</script>
I don't understand why you want to use cookies for this. You should get page1, find the images, and then use setInterval to update the src.
$.get('page1.html', function(data, status) { // get the page with the images
var parser = new DOMParser();
var xmldoc = parser.parseFromString(data, "text/html"); //turn it into a dom
var imgs = xmldoc.getElementsByTagName('img'); //get the img tags
var imageSrcs = Array.prototype.slice.call(imgs).map(function(img) {
return img.src; //convert them to an array of sources
});
setInterval(function() { // run this every 10 seconds
var imags = document.getElementsByTagName('img'); // find the images on this page
Array.prototype.slice.call(imgs).forEach(function(img) {
var imgSrc = Math.floor(Math.random()*imageSrcs.length); //get a random image source
img.src = imageSrcs[imgSrc]; //set this image to the src we just picked at random
});
}, 10000);
}, 'html');
why not use ajax? you could .load() the section of your external page that contains all of the images into a hidden container and then extrapolate the information you need through a callback.
external.html
<html>
....
<div id="imgContainer">
<img id="image0" src="image0.jpg" />
<img id="image1" src="image1.jpg" />
<img id="image2" src="image2.jpg" />
<img id="image3" src="image3.jpg" />
</div>
</html>
ajax.js
function ajaxContent(reg, extReg) {
var toLoad = 'external.html' + extReg;
function loadContent() {
$(reg).load(toLoad,'',getSrcPaths())
}
function getSrcPaths() {
$(reg + ' #image0').delay(200).fadeIn('slow');
$(reg + ' #image1').delay(200).fadeIn('slow');
// or however you want to store/display the images
}
}
Then onload just make a call to ajaxContent something like
<body onload="ajaxContent('#hiddenContainer','#imgContainer')">
....
</body>
This of course is not really relevant if your images are large or if page load is negatively affected. Although since you actually have the images now, you might even just display them rather than hide them. Depends on exactly how much you need to manipulate the originals I suppose.

Categories