How to use JavaScript to put image src into HTML? - javascript

I want to put image src into my code.
This is my JavaScript code so far:
<script>
function images(){
var randomizer = Math.floor((Math.random() * 5)
var pictures =["images1.jpg","images2","images3.jpg","images4.png","images5.jpg"]
}
</script>
and this is my HTML code:
<img id = "bubbles" src="images1.jpg" width="20%" alt = "pics">
<img id = "bubbles2" src="images2.jpg" width="20%" alt= "pics">
The problem that I am facing is that I am not able to put the arrayed string into the src.

The problem is that the src attribute of an image tag can't take in an array of images. You'll need a separate image tag for your photos.
var pictures = ["images1.jpg", "images2", "images3.jpg", "images4.png", "images5.jpg"];
for (var i = 0; i < pictures.length; i++) {
var imgEl = document.getElementById("bubbles");
imgEl.setAttribute("src", imEl[i]);
}
The above code will update the src attribute with the images in the array. However, this will probably so quick you'll only see the last one. You would need to figure out a timing mechanism or integrate your random number function to chose a random image.
Using Math.random()
var pictures = ["images1.jpg", "images2", "images3.jpg", "images4.png", "images5.jpg"];
var randomizer = Math.floor(Math.random() * 5);
var imgEl = document.getElementById("bubbles");
imgEl.setAttribute("src", imEl[randomizer]);

Related

How to change the image a source is associated with

Is there anyway that I can put an image on my site that changes.
I know how to change the source of an image element. What I mean is like:
the image is located here
http://mywebsite.com/image.png
this doesn't change but I want the actual image to change.
More examples:
https://huggle.jdf2.org/
This site creates a bbcode element that contains the img username.png
[url=http://huggle.jdf2.org/hug/username][img]http://huggle.jdf2.org/sig/username.png[/img][/url]
This image changes depending on how many huggles you have.
How would I do this?
You can dynamically set the image source URL with:
var yourURLHere = 'ADD YOUR URL HERE';
image.src = yourURLHere;
If you want the your image to randomly change, you can use Math.random() to select a random URL from an array.
Example: Random teddy bear images (see below).
<image src="#" id="my-image"/>
Click to change image randomly.
<button id="my-btn">Change it!</button>
<script>
var imageURLs = [
'https://s-media-cache-ak0.pinimg.com/originals/4e/da/9f/4eda9f56de08463bcc18d154f654ab6d.jpg',
'http://lcdn.inthelighturns.com/media/product/e85/sweet-memories-blue-teddy-bear-urn-b83.jpg',
'https://s-media-cache-ak0.pinimg.com/originals/3c/80/3c/3c803ce72e8c0325d7ea0fcd32f81ed9.jpg',
'http://cliparting.com/wp-content/uploads/2016/07/Cartoon-teddy-bear-clipart.gif',
'http://cliparts.co/cliparts/rcn/Kox/rcnKox65i.png',
'https://s-media-cache-ak0.pinimg.com/originals/f2/d6/25/f2d6258ef0fa6de2160778066ccec832.jpg',
'https://s-media-cache-ak0.pinimg.com/236x/90/3a/6c/903a6c59c0a2f42e7d6e7cb9427a8337.jpg',
'https://s-media-cache-ak0.pinimg.com/564x/a9/ee/30/a9ee30a4f8d196a111aa5c3db7b13b6e.jpg',
'http://cdn3.volusion.com/9nxdj.fchy5/v/vspfiles/photos/BB-1433-2.jpg?1415360799'
];
var image = document.getElementById('my-image');
function pickRandomURL() {
return imageURLs[Math.floor(Math.random() * imageURLs.length)];
}
image.src = pickRandomURL();
image.width = 200;
var btn = document.getElementById('my-btn');
btn.onclick = function() {
image.src = pickRandomURL();
image.width = 200;
};
</script>

How to make a picture change randomly in a website?

I want to make a website that the user will decide something. The user will click what he or she chose.
I want to know how to make the picture change to a random other picture everytime the user clicks it.
Is there any way to do that?
create an array with all the urls of the images you wanna use.
e.g.
HTML:
<img id='the-image-to-change'/>
JS:
var imageUrls = [
'http://placehold.it/255x255&text=A',
'http://placehold.it/255x255&text=B',
// ... more
'http://placehold.it/255x255&text=Z'
];
if you're not using jQuery:
var img = document.getElementById('the-image-to-change');
img.addEventListener("click", function() {
this.src = imageUrls[Math.floor(Math.random() * imageUrls.length)];
});
if jQuery (has not been tested)
img = $('#the-image-to-change');
img.on('click', function() {
this.src = imageUrls[Math.floor(Math.random() * imageUrls.length)];
});
This should give you the type of effect you want. Basically you're storing your images in an array, then you're going to randomly pick an index, then display it.
var yourImages = ["image1.png","image2.png","image3.png"];
var randomImage = Math.round(Math.random()*yourImages.length);
function displayImage()
{
document.write(yourImages[randomImage]);
}
Here is an example that's more geared toward what you asked, after I read your question again. If the user clicks on the image, it'll change to a random one.
JS:
<img id="currentImage" src="defaultImage.png" onclick="changePicture()">
<script>
function changePicture(){
var yourImages = ["image1.png","image2.png","image3.png"];
var randomImage = Math.round(Math.random()*yourImages.length);
var setImg = document.getElementById("currentImage").src;
setImg = yourImages[randomImage];
}
</script>
jQuery:
<img id="currentImage" src="defaultImage.png">
<script>
$("#currentImage").click(function(){
var yourImages = ["image1.png","image2.png","image3.png"];
var randomImage = Math.round(Math.random()*yourImages.length);
$("#currentImage").attr("src", yourImages[randomImage]);
});
</script>
Create an array of your picture, and use
Math.random();
To select a random index from your picture array that will be shown??

How to create an ascending sequence of text/numbers for html slideshow

I would really appreciate it if anyone could show me how to automate a list/sequence/array for an html slideshow. I want to display "001.gif" through "1869.gif" Obviously it would save a lot of time if there is a way to automatically generate this:
<img src="001.gif" width="640" height="480" />
<img src="002.gif" width="640" height="480" />
<img src="003.gif" width="640" height="480" />
All the way up to "1869.gif"
<img src="1869.gif" width="640" height="480" />
Note: I have a slideshow script that I like. Works perfect. I got to "050.gif" and decided to ask if there is a way to do this without typing them one by one. Thanks.
$(document).ready(function(){
function pad (str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
for(i=1;i < 1870;i++){
var $image = "<img src='"+pad(i, 3)+".gif' width='640' height='480'/>";
$("body").append($image);
}
});
Add this to the end of your page (in tags) or in a separate JS file. Change "body" to the location you want to add your images which will likely be the container you are using for your jQuery.cycle slideshow.
This will loop through each of the numbers between 1 and 1869 and add an image to the body tag for each. The "pad" function adds the zeroes before the number - if you need more info about that, I got the code from Adding extra zeros in front of a number using jQuery?
Since you're not waiting for any other content to load you can create your content instantly.
First extend Number with a pad method:
Number.prototype.pad = function(size) {
var s = String(this);
if(typeof(size) !== "number"){size = 2;}
while (s.length < size) {s = "0" + s;}
return s;
}
Then cache your output before adding it to the page, or you'll cause a redraw for each element you add.
var suffix = ".gif";
var container = document.createElement("div");
for(i=1;i < 1870;i++){
var img = document.createElement("img");
img.width = 640;
img.height = 480;
img.src = i.pad(3) + suffix;
container.appendChild(img);
}
document.body.appendChild(container);

change image and caption

I am trying to work out a way to change the text that goes along with an image that is changed with javascript...
var x = 0;
var images = new Array(".jpg", ".jpg", ".jpg", ".jpg", ".jpg");
var i = setInterval(auto, 10000);
function auto() {
x++;
if (x == images.length) x = 0;
document.getElementById('bigImage').src = images[x];
}
function changeImage(img, imagetitle) {
document.getElementById('bigImage').src = img;
/* document.getElementById('mainimagetitle').innerHtml = imagetitle; */
}​​​
The commented part is how i suppose I could possibly change the text that goes with the image. How do i code the html. Should i use a with the id mainimagetitle?
If so, where and how do i add the different texts i want to show and hide?
As I see from your posting, this should do the job.
<img id="bigImage" src="img1.jpg" alt="" />
<div id="mainimagetitle"></div>
Be sure to add a (filled) src tag or you will get strange results in IE. As you start with the second image (x++ before the change) this will be no problem. Happy accident I think. ;-)
// Edit: Of course any element will do as long as you use the right id. But you didn't tell us what html you use (xhtml/html5/...).
You could potentially have another array that stores the captions for each of the images
var captions = ['Caption 1', 'Caption 2', ...];
Assuming the mainimagetitle is an id of a <p> element, you could do:
function changeImage(img, imagetitle) {
document.getElementById('bigImage').src = img;
document.getElementById('mainimagetitle').innerText = imagetitle;
}​​​
You can see the full example, based on your code here.

Javascript will not load the pictures

I want to load these banner.png files to the screen but all it prints out is the actual text from the banner array?
function randImg(){
var banner = new Array();
banner[0] = 'banner1.png';
banner[1] = 'banner2.png';
banner[2] = 'banner3.png';
maxImg = banner.length;
randNum = Math.floor(Math.random()*maxImg);
return banner[randNum];
}
any thoughts? I think I need to some how add a src but I am not sure how.
Might be too obvious, but...
function randImg(){
var banner = new Array();
banner[0] = 'banner1.png';
banner[1] = 'banner2.png';
banner[2] = 'banner3.png';
maxImg = banner.length;
randNum = Math.floor(Math.random()*maxImg);
return '<img src="' + banner[randNum] + '" />';
}
Demo: http://jsfiddle.net/AlienWebguy/u7yfq/
My pure javascript DOM manipulation is a little fuzzy (usually use jquery) but something like this should do the trick:
<div id="images"></div>
<script type="text/javascript">
function randImg(){
var banner = new Array();
banner[0] = 'banner1.png';
banner[1] = 'banner2.png';
banner[2] = 'banner3.png';
maxImg = banner.length;
randNum = Math.floor(Math.random()*maxImg);
var container = document.getElementById('images');
var img = document.createElement('img');
img.setAttribute('src',banner[randNum]);
container.appendChild(img);
}
</script>
The instruction that loads the image should be like this.
Where imgElement is an IMG element.
imgElement.src = randImg();
If you don’t know how to get an IMG element. Give the IMG element an ID attribute and load this like this.
For an IMG element as <img id="myImage" src="" />
Then:
var imgElement = document.getElementById("myImage");
imgElement.src = randImg();
Note.- my answer gives instruction on how to change the source of an IMG element that exists in the DOM (It is recommended to do so). You should NEVER document.write() an element, Neither on demand or when page is loading. That practice has been deprecated and many browsers would delete the whole page contents if you do so.

Categories