I want JavaScript to load a few img src's on page load. However my solution doesn't seem to work.
Any help would be very appreciated.
HTML
<li><img id="option1" height="45px" width="75px" alt="" src=""></li>
<li><img id="option2" height="45px" width="75px" alt="" src=""></li>
JavaScript
function filltopfoto(){
var settoppic = new Image;
for (var i = 0; i <= itemlist;i++){
settoppic.src = 'img' + i + '.jpg';
$('option' + i).src = settoppic.src;
}
}
FYI:
itemlist contains the amount of images that need to be filled.
The script gets loaded on body load.
Here is the jsfiddle of the code below to show a real example.
images = ["image1/url", "image2/url"] // define image source urls
$(document).ready(function(){ // wait until the document is ready
for(var i = 0; i < images.length; i++) // loop over all images
$('#option'+(i+1)).attr('src', images[i]); // set the src attribute, note the '#'
});
A couple of your mistakes:
JQuery's $('#id') look-up requires the hashtag (#) for ids.
Your filltopfoto() function is never called (Try doing alert('hello!') inside the function).
Your $('options'+i) gives options0 and options1 -- you need options1 and options2
Not sure why you create a new Image just to store a src variable. You can remove this code.
Related
I have an automatic image carousel in javascript for my html website. The carousel has 5 images. The carousel works well on the first round, but on the second round of images, the 1st image doesn't appear. I'm not sure why? Please help if you can
<script>
(function(){
var imgLen = document.getElementById('gallery');
var images = imgLen.getElementsByTagName('img');
var counter = 1;
if(counter <= images.length){
setInterval(function(){
images[0].src = images[counter].src;
console.log(images[counter].src);
counter++;
if(counter === images.length){
counter = 1;
}
},5000);
}
})();
</script>
It works the first time because your first image, which I'm assuming is the displayed image, starts with the correct source.
It appears that you are overwriting the source of this image with the other sources. After the first round, the original source of the first image is lost.
At the moment, your image sources are probably something like:
1,2,3,4,5
2,2,3,4,5
3,2,3,4,5
4,2,3,4,5
5,2,3,4,5
for the first round, which is alright. Once the second round starts however, and for subsequent rounds, it would go something like this:
2,2,3,4,5
3,2,3,4,5
4,2,3,4,5
5,2,3,4,5
The simplest solution would be to store the first image as a 6th image, which would work with your existing code.
An alternative solution would be to store image sources in a JavaScript variable and use those as sources instead of referencing other elements.
It seems that your first image in the set images[0] has its src attribute overwritten every time the setInterval runs, so its source value has been lost. This means it won't be readable again. Rather than using the 0th item in the set to be the display target for your slideshow, try giving it a unique classname (<img class="slideshowTarget" src="...">) and selecting it individually like:
var slideshowTargetImage = document.querySelector('.slideshowTarget');
Rather than using imgLen.getElementsByTagName('img'), try adding a classname to the images you want to cycle in (<img class="slideshowImage" src="...">) and select them with something like:
var images = document.querySelectorAll('.slideshowImage');
Next, you'll want the image list to contain the original image again, or it won't be available in your image list. You should put that item at the end, so it'll be in the correct position when it's time for your slideshow to loop.
<div class="slideshow">
<img class="slideshowTarget" src="0.jpg" />
<div class="slideshowPreloadImages" style="display: none;">
<img class="slideshowImage" src="1.jpg" />
<img class="slideshowImage" src="2.jpg" />
<img class="slideshowImage" src="3.jpg" />
<img class="slideshowImage" src="0.jpg" />
</div>
</div>
Next, you can simplify your logic for the loop into one statement that you can run after you set the source on your image. The %, or "modulo" operator causes the counter to wrap back around to zero as soon as it grows past images.length - 1.
counter = (counter + 1) % images.length;
All together!
(function(){
var slideshowTargetImage = document.querySelector('.slideshowTarget');
var images = document.querySelectorAll('.slideshowImage');
var counter = 0;
var cycleSlideshow = function(){
var nextImageSource = images[counter].src;
slideshowTargetImage.src = nextImageSource;
console.log('nextImageSource', nextImageSource);
counter = (counter + 1) % images.length;
};
if (images.length) { // we can now test whether it's 0/falsy, becacuse the target is not part of the set!
setInterval(
cycleSlideshow,
1000
);
}
})();
I have created a Javascript function which will allow me to change the image to another when the div is directly clicked but I am trying to get this function to work depending on which other image icon i select.
As you can see by the above image, i have a main div which contains a picture on browser load, and two further thumbnail divs which include different pictures, I want to create the function to change the main div if one of the smaller thumbnail divs are selected.
Current Javascript Function
function diffImage(img) {
if(img.src.match(/blank/)) img.src = "bognor.jpg";
else img.src = "images/bognor2.jpg";
}
Thanks in advance,
Sam
You would just use onclick event listeners on the icons and the function would change the large image to the image of the item clicked:
document.getElementById("icon1").onclick = function() {
document.getElementById("mainImage").src = this.src;
}
document.getElementById("icon2").onclick = function() {
document.getElementById("mainImage").src = this.src;
}
If you happen to have several icons you could make an icon class and apply the event listener like so:
var icons = document.getElementsByClassName("icon");
for(var i=0; i<icons.length; i++) {
icons[i].onclick = function(){
document.getElementById("main").src = this.src;
}
}
Fiddle Example for using classes
Although it's easier in that case to use jQuery and simply attach the event handler doing $('.icon').click(function(){ ... }). Of course you are not required to do so.
I recently did something similar where I had a table underneath the feature image of just smaller thumnail images.
$(".browseTable").on('click', 'td', function () {
var thumbNail = $(this).parent('tr').find('img').attr('src');
var feature = $('#featureImg img').attr('src');
$('#featureImg img').fadeOut(400, function () {
$(this).fadeIn(400)[0].src = thumbNail;
});
});
You could put the url of the big image in a custom data-attribute on the thumb element, such as <img src="thumb1.png" data-bigsrc="image1.png" />. Then you can add an event to all thumbnails like this:
var thumbs = document.querySelectorAll('.thumbnail');
var mainImage = document.querySelector('#mainImage');
for(var i=0; i<thumbs.length; ++i) {
thumbs[i].addEventListener('click', function(e) {
mainImage.src = e.target.getAttribute("data-bigsrc");
});
}
If you have high quality images and actually want to make them load when the user clicks, you could also use a radio button for each image, with the value set to the URL of the big image. Make the radio buttons invisible and put the thumbnails inside labels. Then you can just bind an event listener to all radio buttons and make them change the main image URL based on the radiobutton value.
Or if you want all the images to load in advance, you should just make tons of big-small image pairs and make the big image only visible if the small image's radiobutton is clicked, making an all-css solution.
As an alternative, this uses vanilla JavaScript, and three different ways of storing/naming the image files are covered.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div id="divMainImage">
<img id="mainImage" src="/images/image01Main.jpg" alt="Main image" />
</div>
<div id="divThumbnails">
<img class="thumb" src="/images/image01.jpg" alt="image01 thumbnail" />
<img class="thumb" src="/images/image02.jpg" alt="image02 thumbnail" />
<img class="thumb" src="/images/image03.jpg" alt="image03 thumbnail" />
</div>
<script type="text/javascript">
// Name both small and large images the same but with a prefix or suffix depicting thumbnail/main:
// image01.jpg (image01small.jpg) or image01Main.jpg (image01.jpg)
// image02.jpg (image02small.jpg) or image02Main.jpg (image02.jpg) etc.
// Or use two folders - one with main images, the other with thumbnails - both files named the same,
// then swap the folder to use when getting the image.
// Then use the displayed thumbnails' class to load originals:
var thumbnails = document.getElementsByClassName("thumb");
var mainImage = document.getElementById("mainImage");
for (index in thumbnails)
{
thumbnails[index].onclick = function () {
// Depending on the way used use on of the following:
mainImage.src = this.src.replace('.jpg', 'Main.jpg');
// Or
// mainImage.src = this.src.replace('thumb.jpg', '.jpg');
// Or
// mainImage.src = this.src.replace('/images/small/', '/images/large/');
}
}
</script>
</body>
</html>
I am currently having problem displaying multiple images using only one img tag and whose src is changed continuously. Here is my code:
<script>
var i=0;
function swapImage() {
document.slide.src = 'image'+i+'.jpg';
i++;
setTimeout('swapImage()',3000);
}
</script>
<img class='materialboxed' width='350px' height='250px' src='CCTV.jpg' name='slide'>
But my code only displays one image then shows it in a kind of slideshow but rather i want to display all of them at once in a kind of for and while loop if possible.
The thing is, you have not executed swapImage yet.
var i = 0;
(function swapImage() {
document.slide.src = 'image' + i + '.jpg';
i++;
setTimeout('swapImage()', 3000);
})();
Maybe you should use id instead of name (<img src="" ... id="slide" />) for the image and then use document.getElementById('slide').src = ....
I wanted a way to load images only when needed but am hesitant to use AJAX. Instead, will something like this work?
<div onclick="loadimages()">Section Title</div>
<script type="text/javascript">
function loadimages()
{
document.write('<img src="images/thumbnail1.jpg" />');
document.write('<img src="images/thumbnail2.jpg" />');
document.write('<img src="images/thumbnail3.jpg" />');
}
</script>
The intent is for the images to appear below the "Section Title" when that div is clicked, and for the images to be loaded only at that time.
If you want to add elements to the DOM dynamically there are several choices much more preferable than the abhorrent document.write. For example, you can do this:
var image = document.createElement("img");
image.src = "images/thumbnail1.jpg";
var parent = document.getElementById("foo"); // identify the parent somehow
parent.appendChild(image);
Or you could do this:
var parent = document.getElementById("foo"); // identify the parent somehow
parent.innerHTML += '<img src="..." />';
Or, if you use jQuery:
$("your selector here").append('<img src="..." />');
Edit: Untested code -- typed on the fly.
document.write won't do what you want after the page has loaded, you'd have to do something with the DOM..
Like, perhaps:
<div id='section_title' onclick="loadimages()">Section Title</div>
<script type="text/javascript">
function loadimages()
{
var pics = ['thumbnail1.jpg', 'thumbnail2.jpg', 'thumbnail3.jpg'];
var i, img, el;
el = document.getElementById('section_title');
for (i = 0; i < pics.length; i++) {
img = document.createElement("img");
img.src = pics[i];
el.appendChild(div);
}
}
</script>
Another way would be to put the images in your HTML file, but with display:none to hide them and unhide as needed.
Or, depending on the purpose, put them in the HTML as normal, then hide them on load and unhide then when needed.
When you do document.write('something');
This something will replace entire contents of your document.
What you can do is, create new elements dynamically and append them at appropriate places.
i need to know when a special html element containing images has been fully loaded.
The problem with this html element is that it gets replaced fully in the DOM on button click.
What can i do? (i do not want to assign a handler to each of the containing images btw.)
pretty ugly, but working
var soManyImgsInHere = 0;
var fooAttachEvent = function(whereAreTheImages_Container){
var where = whereAreTheImages_Container; //shorthand
var length = where.length;
soManyImgsInHere = length;
var imgs = where.getElementsByTagName('img');
for(var i=0;i<length;i++){
imgs[i].onload = function(){
soManyImgsInHere--;
if(soManyImgsInHere == 0){
alert('all imgs fully loaded'); // do whatever you want here :) all images are now fully loaded
}
}
};
let's assume your images are in a div with the id "fooImages"
then simply use this function right under this div like that:
<div id="fooImages">
<img src="1.jpg" />
<img src="2.jpg" />
<img src="3.jpg" />
</div>
<script>fooAttachEvent(document.getElementById('fooImages'));</script>
Hope this helps :)