I have created an HTML file which uses java script to display images randomly displayed in 3 div tags. On click the images move left or right. It works fine until I use single slideshow in the page, but creates problem when I try multiple slideshows on the same page.
Here is the code for one slide show :
**<script>
currentIndx = 2;
MyImages=new Array();
MyImages[0]='1images2.jpeg';
MyImages[1]='1images3.jpeg';
MyImages[2]='1images4.jpeg';
MyImages[3]='artwork.jpg';
MyImages[4]='1images5.jpeg';
imagesPreloaded = new Array(4)
for (var i = 0; i < MyImages.length ; i++)
{
imagesPreloaded[i] = new Image(120,120)
imagesPreloaded[i].src=MyImages[i]
}
/* we create the functions to go forward and go back */
function Nexter()
{
if (currentIndx<MyImages.length-1){
alert(currentIndx);
document.leftimg.src=document.middleimg.src
document.middleimg.src=document.rightimg.src
document.rightimg.src=imagesPreloaded[++currentIndx].src
}
else {
alert("In nexter else")
currentIndx=0
document.leftimg.src = document.middleimg.src
document.middleimg.src = document.rightimg.src
document.rightimg.src = imagesPreloaded[currentIndx].src
}
writeImageNumber();
}
function Backer()
{
if (currentIndx>0)
{
--currentIndx;
alert("In Backer If");
document.rightimg.src=document.middleimg.src
document.middleimg.src=document.leftimg.src
document.leftimg.src=imagesPreloaded[currentIndx].src
}
else
{
currentIndx = MyImages.length-1
alert(MyImages.length +"else");
document.rightimg.src = document.middleimg.src
document.middleimg.src = document.leftimg.src
document.leftimg.src = imagesPreloaded[currentIndx].src
}
writeImageNumber();
}
/*###### function to reload the images and text when refresh is pressed ##### */
function setCurrentIndex()
{
currentIndx=0;
document.theImage.src=MyImages[0];
document.form1.text1.value=Messages[0];
writeImageNumber();
}
</script>
<body onload="setCurrentIndex();automaticly()">
<!-- start of form for image slide show ####################### -->
<div id ="left" style="float:left">
<a href="#" onclick="Backer()" ><img src="1images2.jpeg" width="265" height="262"
border="0" name="leftimg"></a>
</div>
<div id ="middle" style="float:left">
<a href="#" onclick=""><img src="1images3.jpeg" width="265" height="262"
border="0" name="middleimg"></a>
</div>
<div id ="right" class="compimg" style="float:left">
<a href="#" onclick="Nexter()" ><img src="1images4.jpeg"
width="265" height="262" alt="" border="0"name="rightimg"></a>
</div>
<!-- end of form for image slide show ####################### -->**
Any suggestions...
You haven't wrapped your script in any javascript class(object) so all variables you are using have global scope(page level). I guess your variables are over written if you try to use it multiple time.
You can get better answer if you post HTML markup of how you are trying to create multiple slideshow in single page...
Related
I want to create a basic page in html that displays a single image.
I also added two buttons Previous and Next. These buttons should allow the user to move forward or backward. Have 6 images in total. When the user reaches the end (or beginning when clicking on the back button) of the slide show, the slide show should not wrap around to the beginning (or end).
button onclick function for both the cases is not working. Its only getting displayed the first image as what mentioned in the img src attribute.
This is what I have done so far. I put all the images into an array and try to travel the array forward and backward side based on the button click.
<body>
<img src="img1.jpg" id="demo" style="width:400px;height:600px"/img>
<br/>
<input type="button" onclick="preImage()" value="Previous
">
<input type="button" onclick = "nextImage()" value="Next
">
<script>
var slider_content = document.getElementById("demo");
var image = ['img1','img2','img3','img4','img5','img6'];
var i = image.length;
function nextImage(){
if(i<image.length){
i=i+1;
}else{
i=1;
}
slider_content.innerHTML="<img src="+image[i-1]+".jpg>";
}
function preImage(){
if(i<image.length+1 && i>1){
i=i-1;
}else{
i=image.length;
}
slide_content.innerHTML = "<img src="+image[i-1]+".jpg">
}
</script>
</body>
Create a wrapper div to your image and change the innerHTML of the div.
<div id="demo" style="width:400px;height:600px">
<img src="img1.jpg">
</div>
An error needs to be corrected in the preImage function:
slide_content.innerHTML = "<img src="+image[i-1]+".jpg">
to
slider_content.innerHTML = "<img src="+image[i-1]+".jpg>";
and also what Daniel said.
After trying several lightbox variations and in the interest of getting back in practice and learning JQuery, decided to try coding my own http://walczak.000webhostapp.com/index.html. The hosting site for a project I'm working on looks to also be loading some form of JQuery. The behavior I'm seeing happens on the 3D pages where I need to present a gallery of images. The first time a gallery is opened, both clicking on a thumbnail image and using the Next / Previous buttons works as expected. However when a second gallery instance is opened, when using the Next / Previous buttons, every other image seems to be shown. 3rd time, every 3rd image. Debugging shows that JQuery is running multiple times. I have tried suggestions from click() event is calling twice in jquery with no success.
Also help with why a thumbnail needs to be clicked before the Next / Previous buttons will work (did not have this problem at first) and what I may have missed to solve the dreaded TypeError cannot read property inside the document.ready function on the thumbnail array would be appreciated. relevant code is:
On main page
<div class="boxback">
<div class="box">
<table>
<tr>
<td><a id="prev" href="#"><img class="galleryNav" src="./backgrounds/buttons/lightbox/back.png"></a></td>
<td><img id="imgbox" src="" alt=""></td>
<td><a id="next" href="#"><img class="galleryNav" src="./backgrounds/buttons/lightbox/forward.png"></a></td>
</tr>
<tr>
<td></td>
<td><p id="caption"></p></td>
<td></td>
</tr>
</table>
<div id="thumbs"></div>
<a id="myClose" href="#"><img src="./backgrounds/buttons/lightbox/close.png"></a>
</div>
</div>
...
Loaded content
<ul class="thumbsdiv">
<li class="clkthumb"><img class="thumbnail" src="./davinci/large/gears/gearsmain.png" alt="Original DaVinci drawing" data-index=0></a></li>
<li class="clkthumb"><img class="thumbnail" src="./davinci/large/gears/gears01.png" alt="" data-index=1></a></li>
<li class="clkthumb"><img class="thumbnail" src="./davinci/large/gears/gears02.png" alt="" data-index=2></a></li>
<li class="clkthumb"><img class="thumbnail" src="./davinci/large/gears/gears03.png" alt="" data-index=3></a></li>
(abbreviated ...)
</ul>
JQuery
var mypath = "";
var myindex = Number(0);
//var imgs = [];
$(document).ready(function()
{
$(".overlay").click(function()
{
mypath = $(this).attr("data-gallery");
mypath += " .thumbsdiv";
$("#thumbs").load(mypath);
$(".boxback").css("display","block");
$(".box").css("display","inline-block");
$("#imgbox").attr("src",$(this).attr("data-image"));
$("#imgbox").attr("alt",$(this).attr("data-alt"));
$("#caption").text($(this).attr("data-alt"));
myindex = Number($(this).attr("data-index"));
do{
if (document.readyState === "complete")
{ $(document).on("click",".thumbnail",thumbClick);
$(document).on("click","#prev,#next",nextImg);
$(".thumbnail")[myindex].trigger("click");
//$('[data-index = "0"]').click();
}
} while(document.readyState !== "complete");
})
});
function thumbClick()
{
// $("#imgbox").attr("src","");
// $("#imgbox").attr("alt","");
$("#caption").text("");
$("#imgbox").attr("src",$(this).attr("src"));
$("#imgbox").attr("alt",$(this).attr("alt"));
myindex = Number($(this).attr("data-index"));
$("#caption").text($(this).attr("alt"));
$(".thumbnail").css({"border-style":"none"});
$(this).css({"border-style":"solid",
"border-color":"#000",
"border-size":"1px"});
event.stopImmediatePropagation();
};
//$("#prev,#next").click(function nextImg()
function nextImg()
{
var imgs = $(".thumbnail");
if ($(this).attr("id") == "next")
{myindex++;}
else {myindex--;}
if (myindex <= -1)
{myindex = imgs.length - 1;}
if (myindex >= imgs.length)
{myindex = 0;}
imgs[myindex].click();
};
I'm trying to create a JavaScript that will randomize images on page refresh. I'm not really familiar with JS so I've been having a bit of trouble.
I've succeeded in building a successful program by hard coding the image url sources into the JS array, but this is not a possibility for what I am coding this for because the user will dictate what set of images will display. The user will not have access to the JS. So the array would get the image sources from the html. What I've been trying to do is use "getElementByClassName" and insert into the array by for loop. But it doesn't seem to be working. I'm sure there is a more efficient way to do this as well, so feel free to enlighten me.
Here is the code I have so far:
<!-- Images to put into JS Array -->
<img class="header" src="/image1.jpg" style="display: none;" />
<img class="header" src="/image2.jpg" style="display: none;" />
<img class="header" src="/image3.jpg" style="display: none;" />
<!-- Image placeholder -->
<img src="/image1.jpg" id="rotate" />
And the JavaScript in a separate document:
// Javascript code
window.onload = chooseHeader;
var imgs = document.getElementsByClassName("header");
var headers = new Array();
for (var i = 0; i < imgs.length; i++) {
headers.push(imgs[i].src);
}
function chooseHeader() {
rand = Math.floor((Math.random() * headers.length));
document.getElementById("rotate").src = headers[rand];
}
Any advice will be appreciated!
Your code is probably running before the DOM has loaded.
You don't actually need an Array for this, and since getElementsByClassName returns a "live list", you can fetch the images before they exist, and they'll appear when they're loaded in the document.
So if that's the case, a solution is to get the src directly from imgs.
window.onload = chooseHeader;
// live list
var imgs = document.getElementsByClassName("header");
function chooseHeader() {
var rand = Math.floor((Math.random() * imgs.length));
document.getElementById("rotate").src = imgs[rand].src;
}
<img class=header src="https://dummyimage.com/50/f00/fff.jpg">
<img class=header src="https://dummyimage.com/50/0f0/fff.jpg">
<img class=header src="https://dummyimage.com/50/00f/fff.jpg">
<br><br>
Rotate:
<br><br>
<img id=rotate src="">
Online example of my goal:
I'm trying to display bike products on a category page. On each product there's a frame variant color, I'm displaying that using round divs.
When I click a color, the image should change as you can see on Specialized website: (underneath the product image) Specialized Example.
My own website
You can see my own example here: My own website example (scroll down till you see the product with multiple products).
My target functionality:
When I click the GREEN div I'd like to show picture 2 and when I click the RED div I'd like to see image 3, but as Default it will always be the firs
The first color = the first image
The second color = the second image
And so forth
My HTML:
<div class="frameColors">
<div class="frameColor" data-color="#95BD40" style="background-color:#95BD40"></div>
<div class="frameColor" data-color="#000000" style="background-color:#000000"></div>
<div class="frameColor" data-color="#C6352D" style="background-color:#C6352D"></div>
</div>
<a href="/produkter/cykler/mountain-bikes/specialized/epic-hardtails/epic-hardtail/">
<div class="categoryImage" data-frame-color="95BD40">
<img src="/media/1072/165519.jpg?anchor=center&mode=crop&width=500&height=350&rnd=131200748910000000" class="productImage">
</div>
<div class="categoryImage" data-frame-color="000000">
<img src="/media/1071/165518.jpg?anchor=center&mode=crop&width=500&height=350&rnd=131200746750000000" class="productImage">
</div>
<div class="categoryImage" data-frame-color="C6352D">
<img src="/media/1073/166762.jpg?anchor=center&mode=crop&width=500&height=350&rnd=131200749050000000" class="productImage">
</div>
</a>
My Foreach(s):
var imageIds = item.GetPropertyValue<string>("productImages").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
var images = Umbraco.Media(imageIds);
<div class="frameColors">
#foreach (var bikeColor in images)
{
var color = bikeColor.GetPropertyValue("frameColor");
<div class="frameColor" data-color="##color" style="background-color:##color"></div>
}
</div>
<a href="#item.Url">
#foreach (var img in images)
{
<div class="categoryImage" data-frame-color="#img.GetPropertyValue("frameColor")">
<img src="#img.GetCropUrl("product image")" class="productImage" />
</div>
}
</a>
Based on Adeneo reply I managed to modify the code a little so it worked out as I wanted.
First, I added a css line: .categoryImage { display:none; } to hide ALL the product images.
I then added the script based on Adeneo's reply. I start off with targeting EACH of the .frameColor divs and inside that, I added this the following line to show the first image: categoryImage.first().show();
If the CSS line is not included, all of the product images will be displayed by default, so it was necessary to HIDE all the images and inside the script, show the first image.
$(function () {
$(".frameColor").each(function () {
var categoryImage = $(this).parent("div").next("a").find(".categoryImage");
categoryImage.first().show();
if ($(categoryImage).length > 1) {
$(this).on('click', function () {
var color = $(this).data('color').replace('#', '');
$(categoryImage).hide().filter(function () {
return $(this).data('frame-color') === color;
}).show();
});
}
else {
$(this).hide();
}
});
});
Credits goes to Adeneo for providing the original script.
I have 4 thumbnails to the left, and when I click on one of them I waht to show a large picture to the right on the screen.
My problem is, that for some reason it shows 8 small thumbnails (first 4 and then 4 again). The first four ones are not clickable. The last four ones are clickable and correctly shows the larger image.
So, where does the first four thumbnails come from, and how do I get rid of them?
I have a transparant image (Picture.gif) that is the larger picture that is changed and shows the bigger versions of the thumbnails.
My html:
<body onLoad="init()">
<table class="planes">
<tr>
<td>
<ul>
<div id="thumb">
<li><img src="img/Plane1.jpg" alt="Plane1"></li>
<li><img src="img/Plane2.jpg" alt="Plane2"></li>
<li><img src="img/Plane3.jpg" alt="Plane3"></li>
<li><img src="img/Plane4.jpg" alt="Plane4"></li>
</div>
</ul>
</td>
<td>
<img class="pic" id="main" src="img/Picture.gif" alt="">
</td>
</tr>
</table>
My javascript:
var images= new Array('img/Plane1.jpg', 'img/Plane2.jpg', 'img/Plane3.jpg', 'img/Plane4.jpg');
var imgList = new Array();
function init()
{
for (var i=0; i<images.length; i++)
{
imgList[i] = new Image();
imgList[i].src = images[i];
document.getElementById('thumb').appendChild(imgList[i]);
imgList[i].addEventListener("click", swap, false)
}
}
function swap(evtObj)
{
var imgfile = evtObj.target.getAttribute('src');
var mainTag = document.getElementById('main');
mainTag.src = imgfile;
}
In this line:
document.getElementById('thumb').appendChild(imgList[i]);
You are appending the image to the 'thumb' list again. But these are the ones you want to keep, as they have the eventListener attached to them.
You need to remove the tags from your html code to achieve the desired result.
<li><img src="img/Plane1.jpg" alt="Plane1"></li>
<li><img src="img/Plane2.jpg" alt="Plane2"></li>
<li><img src="img/Plane3.jpg" alt="Plane3"></li>
<li><img src="img/Plane4.jpg" alt="Plane4"></li>
The first 4 images are the ones you have in your static html code. The next 4 are the dynamic generated from javascrip. Just remove the images inside thumb from your html code.
The images are both in your html, and also created in javascript.
The line document.getElementById('thumb').appendChild(imgList[i]); adds each image specified in the images array of your javascript to the page.
I suggest you will want to remove the ones in your html - simply remove the <li> tags and the images that are within them.
After taking out the unneeded tags, your HTML should look something like this:
<body onLoad="init()">
<table class="planes">
<tr>
<td>
<div id="thumb">
</div>
</td>
<td>
<img class="pic" id="main" src="img/Picture.gif" alt="">
</td>
</tr>
</table>
First, div cannot be a child of ul and second you shouldn't really use tables for layout (unless making an email template).
If you are just trying to change the src of the main image on the click of the thumbnails, you can use the following js:
var images = new Array('img/Plane1.jpg', 'img/Plane2.jpg', 'img/Plane3.jpg', 'img/Plane4.jpg'),
thumbnails = document.getElementById('thumb').getElementsByTagName('img'),
mainImage = document.getElementById('main');
for (i = 0; i < thumbnails.length; i++) {
setClickFunction(i);
}
function setClickFunction(currentIndex) {
thumbnails[currentIndex].onclick = function() {
mainImage.src = images[currentIndex];
};
}
Example
Using links for your large images instead of an array