I want to pull image from local folder on button click, for which I have created a array with images names, and display it in the <div>.
Here is code example.
<div id="slider"></div>
<button class="btn"></button>
var img = document.createElement('IMG');
img.setAttribute('src', 'img/' + images + ".jpg");
var images = ['photo0', 'photo1', 'photo2'];//photo0.jpg,photo1.jpg,photo2.jpg are images in folder with path img/
var btn = document.querySelecotr('.btn'); //button element with onclick function
var slider = document.getElementById('slider'); //div element in which imgs will be displayed
var i = 0;
slider.appendChild(images[i]);
if (i < images.length)
i++;
else{
i=0;
}
slider.appendChild(images[i]);
Here's what you need, i quoted your images name, and made a for loop to loop through images names, and then created element, added attribute of image path (src), and then appended child to a slider.
function add_images_to_slider(){
var images = ["photo0", "photo1", "photo2"];
var slider = document.getElementById('slider');
for(var i=0; i<images.length; i++) {
var img = document.createElement('img');
img.setAttribute('src', 'img/' + images[i] + ".jpg");
slider.appendChild(img);
}
}
<div id="slider"></div>
<button id="btn" onclick="add_images_to_slider();">click me</button>
If you need one image per click, here is solution:
function add_images_to_slider(){
var images = ["photo0", "photo1", "photo2"];
var slider = document.getElementById('slider');
if (slider.getElementsByTagName('img')[0] !== undefined) slider.removeChild(slider.getElementsByTagName('img')[0]);
if (typeof add_images_to_slider.st_i == 'undefined') add_images_to_slider.st_i=0;
var img = document.createElement('img');
img.setAttribute('src', 'img/' + images[add_images_to_slider.st_i] + ".jpg");
slider.appendChild(img);
if (add_images_to_slider.st_i < images.length-1) add_images_to_slider.st_i++;
else add_images_to_slider.st_i = 0;
}
<div id="slider"></div>
<button id="btn" onclick="add_images_to_slider();">click me</button>
In the second solution i created a static variable at function, which increment untill reached the total of images in array, then restart it self.
EDITED:
I've just appended removing last image from slider, by adding this code:
if (slider.getElementsByTagName('img')[0] !== undefined) slider.removeChild(slider.getElementsByTagName('img')[0]);
Related
Okay so I must create an infinite auto-scrolling horizontal image marquee using vanilla JS. I have the following code:
//if(painkiller<14){painkiller++;} else{painkiller=0;backup2()}
var speed = 5;
var exeggcute = true;
var painkiller = 0;
var marquix = document.getElementById("marquis");
var backup = "";
var coquus = 0;
for (var painkiller = 0; painkiller < 15; painkiller++) {
backup += "<img class='slide' src='" + ImgArray[painkiller].src + "' width='" + ImgArray[painkiller].width + "'>";
}
marquix.innerHTML = backup;
function riverflow() {
marquix.scrollLeft += 5;
if (marquix.children[0].getBoundingClientRect().left <= (marquix.children[0].width * -1)) {
marquix.appendChild(marquix.children[0]);
//marquix.getBoundingClientRect().left=0;
//marquix.children[0].style.transform="translateX(133px)"
}
}
//function backup2(){marquix.innerHTML=backup;}
setInterval('riverflow()', 50);
exeggcute = true;
<head>
<script>
var ImgArray = [];
for (var i = 0; i < 15; i++) {
ImgArray[i] = new Image();
ImgArray[i].src = "imgx/imagen" + (i + 1) + ".jpg";
ImgArray[i].width = 133;
}
</script>
</head>
<body>
<div id="marquis">
</div>
</body>
Basically I'm creating the image chain, then filling with it the innerHTML of a div, then assigning said div to a variable, and finally calling a repetitive function through setInterval(). Now, what that function does is a simple scroll to the left and - when the first image is completely out of the viewport - use appendChild to rip the first child element or img from the image chain then put it at the end of it. So no image overcharge is produced and the marquee uses the same 15 element once and again.
Here's my problem, though: when the appendChild function fires, the image that's out of the viewport is removed, however, the next image in line - as well as the rest of the chain - does not preserve its current position, and is instead forcefully scrolled to fill the gap left by the then-first image that's now at the end. Thus, the condition of the appendChild (which was the first children of the div being completely out of the viewport) becomes true and activates the function - leading the whole marquee to slide non-stop and out of control, as the appendChild is firing continuously.
How can I fix it?
Possible solutions:
You will need to reset the scrollLeft to 0 on the same moment that you switch the images.
You will need to add some element (another img for example at the begining) it could be all white or transparent. That image will be always there, before the firstone visible. When you remove the other image this auxiliar image need to be wider (change the width) to fill the gap, so add to its width the width of the removed image each time you remove one.
Or you can change the marginLeft of the leftmost image with marquix.children[0].style.marginLeft = n + "px";
That's what I came up with, but as I said, the translateX() parameter increases ad infinitum.
<script>
var ImgArray=[];
for (var i=0; i<15; i++){
ImgArray[i]= new Image();
ImgArray[i].src= "imgx/imagen"+(i+1)+".jpg";
ImgArray[i].width=133;
}
</script>
</head>
<body>
<div id="marquis">
<script>
//if(painkiller<14){painkiller++;} else{painkiller=0;backup2()}
var exeggcute= true;
var painkiller=0;
var marquix = document.getElementById("marquis");
var backup=""; var coquus=0;
for(var painkiller =0;painkiller<15;painkiller++){
backup+="<img class='slide' src='"+ImgArray[painkiller].src+"' width='"+ImgArray[painkiller].width+"'>";
}
marquix.innerHTML=backup;
var slidin=133;
function riverflow(){
marquix.scrollLeft+=10;
if (marquix.children[0].getBoundingClientRect().left<=(marquix.children[0].width*-1) && exeggcute){
marquix.appendChild(marquix.children[0]);
marquix.getBoundingClientRect().left=0;
for (var j=0; j<15; j++){
marquix.children[j].setAttribute("style","transform: translateX("+slidin+"px)")
}
slidin+=133;
}
}
//function backup2(){marquix.innerHTML=backup;}
setInterval('riverflow()',50);
exeggcute=true;
</script>
I am trying to write some JS so that the end result adds this to the HTML. I plan to have an array of images to index through and populate the page with images. Is there a simple way of doing this? Will I need to switch the classes to IDs for each image?
<div class="box">
<div class="boxInner">
<img src="http://placehold.it/480x480"/>
</div>
</div>
I have figured out how to add a div with a class.
var newInner = document.createElement('div');
newInner.className = 'boxInner';
document.getElementById("wrap").appendChild(newInner);
I also figured out how to append an image. I am stuck trying to put all of these together.
var newImage = document.createElement("img");
newImage.setAttribute("src", "http://placehold.it/480x480");
document.getElementById("wrap").appendChild(newImage);
This is one way of doing it.
var images = ["http://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg", "http://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg", "http://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg", "http://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg"];
for (var i = 0; i < images.length; i++) {
var container = document.getElementById("container");
var imgElement = document.createElement("img");
imgElement.src = images[i];
container.appendChild(imgElement);
}
<div id="container"></div>
Assuming you have an array with the img srcs and a div with the id of 'box':
var box = document.getElementById('box');
for (var i = 0; i < imgs.length; i++) {
var newInner = document.createElement('div');
newInner.className = 'boxInner';
var newImage = document.createElement('img');
newImage.setAttribute('src', imgs[i]);
newInner.appendChild(newImage);
box.appendChild(newInner);
}
I have 2 arrays, an image array and a price array.
I have the images displaying, but I'd like to display the price, which at the moment I have held in the image name, when I mouseover the image, is it possible?
HTML
<section id=main>
<!--populate with images from array-->
<p id="photos" class="product_display">
<script>getImage();</script>
</section>
JS
//image array for products
var imageArray = new Array();
imageArray[0]="images/coffee_prod_1.png";
imageArray[1]="images/coffee_prod_2.png";
imageArray[2]="images/coffee_prod_3.png";
imageArray[3]="images/coffee_prod_4.png";
imageArray[4]="images/coffee_prod_5.png";
imageArray[5]="images/coffee_prod_6.png";
imageArray[6]="images/coffee_prod_7.png";
//price array for products
var priceArray = ["€11.90", "€12.90", "€13.90", "€14.90", "€15.90", "€16.90", "€17.90"];
function getImage(){
var container = document.getElementById("photos");
for (var i=0; i < imageArray.length; ++i) {
var img = new Image();
img.src = imageArray[i];
img.className = "product_details";
img.name = priceArray[i];
container.appendChild(img);
}
}
I thought I might be able to add something like 'img.onmouseover = imageMouseOver(priceArray[i]);' to my getImage function, and then have something inside the function that would display the image name (ideally over the image) on mouseover. I was hoping to apply an opaque colour too so the image name might be clearer.
Any help would be appreciated!
I would suggest creating a container div for each photo, and in each container add your and like another div that contains the price. Set the price divs hidden at first with display:none or something, and then in your javascript add some listeners to show and hide it:
for (var i=0; i < imageArray.length; ++i) {
var img = new Image();
img.src = imageArray[i];
img.className = "product_details";
var container = document.createElement("div");
var price = document.createElement("div");
price.innerHTML = priceArray[i];
//Style your price and image elements so they fit in the container and the price is displayed over the image etc
container.appendChild(price);
container.appendChild(img);
container.onmouseover = function() {
container.getElementByClass("price").style.display = "block";
};
container.onmouseout = function() {
container.getElementByClass("price").style.display = "none";
};
}
You may need to fiddle with the onmouseover/out events a bit if showing the price div messes it up i.e. onmouseover is called on the layer with the highest z index instead of container, I haven't tried it but this should give you a rough idea
Working example here:
http://jsfiddle.net/0vts5291/
HTML
<section id=main>
<!--populate with images from array-->
<p id="photos" class="product_display">
</section>
JS
var imageArray = new Array();
imageArray[0]="images/coffee_prod_1.png";
imageArray[1]="images/coffee_prod_2.png";
imageArray[2]="images/coffee_prod_3.png";
imageArray[3]="images/coffee_prod_4.png";
imageArray[4]="images/coffee_prod_5.png";
imageArray[5]="images/coffee_prod_6.png";
imageArray[6]="images/coffee_prod_7.png";
//price array for products
var priceArray = ["€11.90", "€12.90", "€13.90", "€14.90", "€15.90", "€16.90", "€17.90"];
function getImage() {
var container = document.getElementById("photos");
for (var i = 0; i < imageArray.length; ++i) {
var img = new Image();
img.src = imageArray[i];
img.className = "product_details";
img.name = priceArray[i];
img.title = priceArray[i];
container.appendChild(img);
}
}
getImage();
I'm trying to use JavaScript to list images 01-40 in order automatically.
Like this:
<img src="01.jpg" />
<img src="02.jpg" />
<img src="03.jpg" />
<img src="04.jpg" />
<img src="05.jpg" />
...
I don't want to write each img src manually, as I want to use this on multiple pages
I'd like the image starting and ending number to be variables that I can edit easily.
You need the parent element for imgs:
for ( var i = FIRST_NUMBER ; i < LAST_NUMBER ; i++ ) {
var elem = document.createElement("img");
if ( i < 10 ) {
elem.setAttribute("src", "0"+i+".jpg");
} else {
elem.setAttribute("src", i+".jpg");
}
document.getElementById(PARENT_ID).appendChild(elem);
}
function img_create(startIndex, endIndex) {
for (i = startIndex; i <= endIndex; i++) {
var oImg=document.createElement("img");
oImg.setAttribute('src', i+".jpg");
//other attributes you need
document.body.appendChild(oImg);
}
}
Working example: http://jsfiddle.net/Lw3bjcx4/1/
function createImages(count, elementId) {
// Get the container element where you want to create the images
var element = document.getElementById(elementId)
// Loop count times over to create count image elements
for (var i = 0 ; i < count ; i++) {
// Create a new image element
var imageElement = document.createElement('img')
// Set the source to index.jpg where index is 0,1,2,3.... count
imageElement.setAttribute('src', i + ".jpg")
// Append the new image element to the choosen container.
element.appendChild(imageElement)
}
}
// Test to create 10 images.
createImages(10,"imgs")
You can use like this:
var imgdiv = document.getElementById('imgdiv');
var img = imgdiv.getElementsByTagName('img');
for(var i=0;i<40;i++){
img[i].src=i+'.jpg';
}
Here is an alternative to all other answers, where you don't need to use an id to put images in. Just paste the script tag where you need to have the images. For example, if you put it in a div, the script will automatically insert the images in place.
<script type="text/javascript">
var thisScriptNode = document.currentScript;
for(var i = 1 ; i <= 40 ; i++) {
var img = document.createElement("img");
img.src = ("00" + i).substr(-2) + ".jpg";
thisScriptNode.parentNode.insertBefore(img, thisScriptNode);
}
</script>
You can easily change the number of leading zeros. For example, to get numbers with three characters, replace "00" with "000" and -2 with -3.
var to = 10;
var from = 0;
for (i = from; i < to; i++){
var elem = new Element('img', { src: i + '.jpg' });
document.body.appendChild(elem);
}
it will append to <body> images with names from 0.jpg to 9.jpg
I want to get the id of the image the mouse hovers. But I do not understand how to get the ID. Can some one help me :). TY!
function placeImage(x){
var div = document.getElementById("thumbnails");
div.innerHTML = ""; // clear images
for (var i =0; i <= x; i++) {
var image=document.createElement("img");
image.className += " Atributes";
image.src="images/foto_klein_"+i+".jpg";
image.width="135";
image.height="90";
image.alt="foto_klein_"+i;
image.id="image"+i;
image.position="relative";
div.appendChild(image);
image.style.marginRight = '10px';
_img.push(image);
}
};
With the placeImage function i place the images. Now I want to add an mouse event and change the class of the image who is targeted.
<div id="thumbnails" onmouseover="mouseOver(this);" ></div>
I added a mouse over to all the thumbnails. But I cannot get the id of the image of which the mouse hovers. I want to call the id or change the image.className of that particlair image. But I do not know how to call it. Now it only alerts "thumbnial"
function mouseOver(e){
alert(e.id);
}
Use this keyword:
<div id="thumbnails" onmouseover="mouseOver(this);" ></div>
function mouseOver(e){
alert(e.id);
}
Edit from the comments:
var image=document.createElement("img");
image.className += " Atributes";
image.src="images/foto_klein_"+i+".jpg";
image.width="135";
image.height="90";
image.alt="foto_klein_"+i;
image.id="image"+i;
image.mouseover = mouseOver;
image.position="relative";
div.appendChild(image);
image.style.marginRight = '10px';
_img.push(image);
}
Note the mouseOver function being called when the image is hovered. this will refer to the image element and not the div.
To get the id of an image when you hover over it, try this:
function placeImage(x){
var div = document.getElementById("thumbnails");
div.innerHTML = ""; // clear images
for (var i =0; i <= x; i++) {
var image=document.createElement("img");
image.className += " Atributes";
image.src="images/foto_klein_"+i+".jpg";
image.width="135";
image.height="90";
image.alt="foto_klein_"+i;
image.id="image"+i;
image.position="relative";
image.onmouseover = mouseOver; // <-- Added this
div.appendChild(image);
image.style.marginRight = '10px';
_img.push(image);
}
}
function mouseOver(e) {
alert(this.id);
}
Hope this helps, though I'm not sure about it working on a dynamically added image.
document.ready = function () {
var thumbnails = document.getElementById("thumbnails");
var imgs = thumbnails.getElementsByTagName("img");
for( var i=0; i<imgs.length; i++ ) {
imgs[i].onmouseover = function() {
alert( this.id );
}
}
};