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.
Related
I would like to improve a code that I have in the sidebar of wordpress, where what I want is that every time people enter randomly loads an image. At the moment with the code I have shown below it works, but when I put my page in google speed it says this:
Avoid use: document.write()
link = new Array();
link[0] = '<img src="" width="300" height="408"/>';
link[1] = '<img src="" width="300" height="408"/>';
link[2] = '<img src="" width="300" height="408"/>';
link[3] = '<img src="" width="300" height="408"/>';
random = Math.random() * (link.length);
random = Math.floor(random);
document.write(link[random]);
<div id="bloquewidget"></div>
There doesn't look to be any need for the array or randomness since the link HTMLs are all the same. Create an <a> with createElement, then use a CSS selector to insert it into the document at the appropriate point. You'll need some way to uniquely identify this <div> - use a class if it already has one, or give the div a class, such as link-container:
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'noopener nofollow';
// do you want to add a non-empty src to the a here?
const img = a.appendChild(document.createElement('img'));
img.width = 300;
img.height = 408;
// do you want to add a non-empty src to the image here?
// insert <a> at the bottom of this div:
document.querySelector('.link-container').appendChild(a);
the
document.write(link[random]);
part can be replaced with:
document.body.innerHTML = document.body.innerHTML + link[random];
It is also worth looking into createElement for creating DOM objects like anchors.
Well I found another solution to my problem I leave the code here in case anyone else needs to put in a wordpress a widget with images that are randomly generated with their own link and not using the deprecated code document.write
<div id="bloquewidget">
<a id="a" rel="nofollow noopener noreferrer" target="_blank"><img id="image" /></a>
<script type='text/javascript'>
var images =
[
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
]
function randImg() {
var size = images.length;
var x = Math.floor(size * Math.random());
var randomItem = images[x];
document.getElementById('image').src = randomItem.ImgSrc;
document.getElementById('a').href = randomItem.Href;
document.getElementById("image").height = "408";
document.getElementById("image").width = "300";
}
randImg();
</script>
Hi guys I am a django developer and trying to grab a random img through JS in html like below
img works and it would randomly pick one from the ImageArray.
However, the path will be <img src= '/static/%22%20%2B%20img%20%2B%22'>.
Rather than something I want like <img src= "{% static 'img/indexBg_1.png' %}" >
And the error msg is : GET http://192.168.7.64:8000/static/img/%22%20%2B%20pic%20%2B%20%22%20 404 (Not Found)
Could anyone enlighten me to resolve this problem? Thx!
<script type="text/javascript">
window.onload=function(){
ImageArray = new Array();
ImageArray[0] = 'img/indexBg_1.png';
ImageArray[1] = 'img/indexBg_2.png';
ImageArray[2] = 'img/indexBg_3.png';
var num = Math.floor( Math.random() * 3);
var img = ImageArray[num];
var path = " <img src= '{% static '" + img +"'%}'>"
console.log(img)
console.log(path)
}
</script>
if you want the path, it should be something like:
var path = window.location.href +'/static/'+ img;
but if you want to add image with that path inside div:
var element = document.getElementById("div1");
element.innerHTML=`<img src=${path} />`;
even better to do:
var path = window.location.href +'/static/'+ img;
var myimg = document. createElement("img");
myimg.src = path;
var element = document.getElementById("div1");
element.appendChild(myimg);
Instead of having a ton of if statements, I would like the method to display the correlated image by name, fx. clicking BlackPicture4.gif will turn it into WhitePicture4.gif. The number of the picture is passed on to the method.
I'm new to javascript, so maybe indexes[] don't work as I thought they do.
I have an array of Whitepicures:
imgArray[1] = new Image();
imgArray[1].src = "WhitePicture1.gif";
...
function changePicture(int)
{
var image = document.getElementById('Img' + int); //works
image.src = imgArray[int] //doesn't work
var thefile = "imgArray" + int + ".gif" //also doesn't work
image.src = thefile;
}
I tried so many different ways, but could use help
html: //as requested, but that works fine
<img id="Img1" onclick="changePicture(1)" src="Blackpicture1.gif" width="50" height="50" >
<img id="Img2" onclick="changePicture(2)" src="Blackpicture2.gif" width="50" height="50" >
...
Edit: The problem is solved by adding .src to "= imgArray[int]"
Another thing I didn't think of was I had to assign the array elements INSIDE a function, rather than just on top of the file where I believe only declarations can be made.
This may work im not sure
imgArray[1] = new Image();
imgArray[1].src = "WhitePicture1.gif";
var x;
function changePicture(x) {
var image = document.getElementById('Img' + x);
image.src = imgArray[x].src;
}
I think what you're trying to do might be
function changePicture(int){
document.getElementById('Img'+int+'').setAttribute('src',imageArray[int].src);
}
In this example, the pic with id='1' will be converted into a pic with id='2':
$("img").click(function() {
var x = $(this).attr("id");
x++;
var y = $("#" + x).attr("src");
$(this).html("");
$(this).html("<img src='" + y "'>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="pic1.jpg" id="1">
<img src="pictobereplaced.jpg" id="2">
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>
I have a series of images (named as image_1.jpg, image_2.jpg and so on) in a folder. How can all of the images be joined together to form an HTML page using Javascript?
Just add:
<img src="path/to/your/image_1" alt="image_1" />
<img src="path/to/your/image_2" alt="image_2" />
<img src="path/to/your/image_3" alt="image_3" />
etc...
EDIT:
for(var i = 1 ; i < TOTAL_IMAGES ; i ++ )
{
var img = document.createElement('img');
img.src = "path/to/your/image_" + i;
img.alt = "image number " + i;
document.appendChild(img); // this will append the image to the root element. You might want to use a <div> or something instead.
}