Switching image with Next/Previous buttons - javascript

Is there any way to switch images using next/prev buttons with jQuery? Here's the code:
<div class="prevDiv">
<img src="images/prev.png" alt="previous" />
</div>
<div class="pic" id="picwebd">
<img src="images/portfolio/webdesign/webd1.jpg" class="portPic" />
</div>
<div class="nextDiv">
<img src="images/next.png" alt="previous" />
</div>
I tried modifying this code to my needs: http://jsfiddle.net/x5mCR/16/ but I haven't succeed. I think that incrementing and decrementing number in the image src would be enough, but I can't come up with decent code do this. Google doesn't help neither.

In case anyone reading this post want a different approach still using JQuery fadeIn, Im posting below the code for that.
Here you can find the fiddle for it.
Here's the Javascript Part
//At the start will show the first image
$('#fullimage img.fullimage:first-child').fadeIn();
//Keep track of the image currently being visualized
var curr = $('#fullimage img.fullimage:first-child');
$('#next').on('click', function() {
//Hide Current Image
curr.hide();
//Find Next Image
var next = curr.next();
//If theres no next image (is the last img), go back to first
if (next.length == 0) next = $('#fullimage img:first');
//Fade In
next.fadeIn();
//Save in curr the current Image
curr = next;
return false;
});
$('#prev').on('click', function() {
curr.hide();
var prev = curr.prev();
if (prev.length == 0) prev = $('#fullimage img:last');
prev.fadeIn();
curr = prev;
return false;
});
Here's the HTML part
<div id="fullimage">
<img class="fullimage" src="http://i.imgur.com/RHhXG.jpg" />
<img class="fullimage" src="http://i.imgur.com/p1L2e.jpg" />
<img class="fullimage" src="http://i.imgur.com/NsrI0.jpg" />
<img class="fullimage" src="http://i.imgur.com/Ww6EU.jpg" />
</div>
<label id="prev">previous</label>
<label id="next">next</label>

Here is dynamic and simple script reducing your html code
http://jsfiddle.net/x5mCR/32/
$("#thumbnail a").on('click', function (eve) {
eve.preventDefault();
var link = ($(this).attr("href"));
var content = '<img src="' + link + '"/>';
$("#fullimage").hide().html(content).fadeIn('slow');
});

Remove the anchors with class thumbnail and give the corresponding <img> tags the thumbnail class, then use jQuery click methods for the thumbnail class:
$(".thumbnail").click(function() {
$(".fullimage").src = $(this).attr("src");
});
Make sure you have a single .fullimage in the #fullimage div.
This isn't the same as a next / previous button - but it would fix the JSFiddle that you made.
http://jsfiddle.net/x5mCR/34/

var picNumber = 1;
$(".nextDiv").click(function() {
picNumber++;
if (picNumber > 3) picNumber = 1; // Change 3 to how many pictures there are.
$(".pic img").attr("src", "images/portfolio/webdesign/webd" + picNumber + ".jpg");
});
$(".prevDiv").click(function() {
picNumber--;
if (picNumber < 1) picNumber = 3; // Change 3 to how many pictures there are.
$(".pic img").attr("src", "images/portfolio/webdesign/webd" + picNumber + ".jpg");
});

If I understand correctly, you're trying to use the arrow keys to move back and forth between pictures...so if this is the case, I would recommend taking a look at this post: Binding arrow keys in JS/jQuery
Also, for your convenience, I just took the code from that post and combined it with the function in your fiddle to get this:
$(document).keydown(function (e) {
if (e.keyCode == 39) {
$(".fullimage").hide();
var next = $(this).next();
if (next.length > 0) {
next.fadeIn();
} else {
$('#fullimage img:first').fadeIn();
}
return false;
}
});
In testing it looks like it might need some modification, and also, you would obviously need to create a similar function for when the back button is pressed, but I think if I'm understanding your issue correctly this is a good starting place.

Related

issue: image carousel skips 1st image

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
);
}
})();

Targeting HTML ID's and using jQuery to modify the content

I have this photo switcher below that I want to modify the HTML content using jQuery only. If you click on the "Show Next Photo" link jQuery will replace the "fruits.png" with another image example "airplane.png". (note: No changes to the HTML block is allowed).
I'm not sure how complicated it can be for jQuery. If I could avoid JavaScript, would be perfect.
<!--Do Not Change Inside this DIV-->
<div id="imageSwitcher">
<img src="https://homepages.cae.wisc.edu/~ece533/images/fruits.png" id="fruits" />
<img src="https://homepages.cae.wisc.edu/~ece533/images/tulips.png" id="tulips" style="display:none;" />
<p>Show Next Photo</p>
</div>
Problem:
This is my script below and isn't working properly because when I refresh the page it just shows the airplane.png, and if I click on the link "Show Next Photo" it makes the airplane disapear.
Please give it a try at https://codepen.io/mrborges/pen/QQjJOq
<script>
//Go away fruits.png
document.getElementById('fruits').style.cssText = "display:none;";
$(document).ready(function () {
$('p').click(function () {
$('#imageSwitcher img').attr("src", "https://homepages.cae.wisc.edu/~ece533/images/airplane.png");
//$('#fruits').toggle("hide");
$('#tulips').toggle("slow");
})
});
</script>
<script>
$(document).ready(function () {
let count = localStorage.getItem('count') || 0; // "0, 1, 2" or 0
count = parseInt(count, 10); //If we get it from storage then convert to number
const images = [
"https://homepages.cae.wisc.edu/~ece533/images/fruits.png",
"https://homepages.cae.wisc.edu/~ece533/images/tulips.png",
"https://homepages.cae.wisc.edu/~ece533/images/airplane.png"
];
$('#fruits').attr("src", images[count]);
$('p').click(function () {
count = (count + 1) % images.length;
$('#fruits').attr("src", images[count]);
localStorage.setItem('count', count);
});
});
</script>
The const images is a list (array) of links to the switch between. I added all the possible images and then i just change the src for each image. a pure jQuery solution would be very ugly, so you have to accept some vanilla JavaScript.
this line count = (count + 1) % images.length counts 1 up each time you click on the <p> if we reach the end of the images, then it just resets to 0. e.g. (2 + 1) % 3 = 0

jQuery CrystalsCollector Game

I created a Crystal Collector game where you have to click a crystal and get to a random number based on each crystal having a hidden value. In my click functions I can have 4 different click functions for each crystal but would like to consolidate 4 actions into one function. Here are the two snippets of code for the HTML and javascript pages we need to complete this:
HTML......
<div class="buttons">
<img class="image" id="image1" src="assets/images/crystal1.png">
<img class="image" id="image2" src="assets/images/crystal2.png">
<img class="image" id="image3" src="assets/images/crystal3.png">
<img class="image" id="image4" src="assets/images/crystal4.png">
</div>
javaScript.....
$(document).ready(function() {
var random = Math.floor(Math.random()*102+19);
$("#numberToGet").text(random);
var num1 = Math.floor(Math.random()*12+1);
var num2 = Math.floor(Math.random()*12+1);
var num3 = Math.floor(Math.random()*12+1);
var num4 = Math.floor(Math.random()*12+1);
var userTotal= 0;
var wins = 0;
var losses = 0;
$("#numberWins").text(wins);
$("#numberLosses").text(losses);
function reset() {
random = Math.floor(Math.random()*102+19);
console.log(random);
$("#numberToGet").text(random);
var num1 = Math.floor(Math.random()*12+1);
var num2 = Math.floor(Math.random()*12+1);
var num3 = Math.floor(Math.random()*12+1);
var num4 = Math.floor(Math.random()*12+1);
userTotal = 0;
$("#score").text(userTotal);
}
function winner() {
alert("You Won!!");
wins++;
$("#numberWins").text(wins);
reset();
}
function loser() {
alert("You Lose!!");
losses++;
$("#numberLosses").text(losses);
reset();
}
$("#image1").on("click", function() {
userTotal = userTotal + num1;
console.log("New userTotal " + userTotal);
$("#score").text(userTotal);
if (userTotal === random) {
winner()
}
else if (userTotal > random) {
loser()
}
})
});
For the bottom "image1" click function, I want to apply this to all 4 crystals each still having a different hidden value. I included a class "image" for each picture and thought if I called the click function for the class "image" and then somehow created a value attribute for the random number each crystal is worth in there somewhere that this would achieve what I want. Any advice to push me in the right direction would help greatly!
There are many ways, but you could do something like...
//....
var crystalValues = {};
crystalValues[1] = Math.floor(Math.random()*12+1);
crystalValues[2] = Math.floor(Math.random()*12+1);
crystalValues[3] = Math.floor(Math.random()*12+1);
crystalValues[4] = Math.floor(Math.random()*12+1);
//.... more code here
function getCrystalHandler(crystalKey) {
return function() {
userTotal = userTotal + crystalValues[crystalKey];
console.log("New userTotal " + userTotal);
$("#score").text(userTotal);
if (userTotal === random) {
winner()
}
else if (userTotal > random) {
loser()
}
}
}
$("#image1").on("click", getCrystalHandler(1));
$("#image2").on("click", getCrystalHandler(2));
$("#image3").on("click", getCrystalHandler(3));
$("#image4").on("click", getCrystalHandler(4));
Not sure if this is what you are going for but if you are creating the crystals in html then go ahead and assign them all a class. So that way they are all apart of class="crystals". Next you want to give them an onclick handler. So to catch you up it should look like this.
<img class="crystals" onclick="popCrystal(event, 'image1')" id="image1" src="assets/images/crystal1.png">
<img class="crystals" onclick="popCrystal(event, 'image2')" id="image2" src="assets/images/crystal1.png">
<img class="crystals" onclick="popCrystal(event, 'image3')" id="image3" src="assets/images/crystal1.png">
<img class="crystals" onclick="popCrystal(event, 'image4')" id="image4" src="assets/images/crystal1.png">
and then we will make a function called popCrystal to be called when someone clicks a crystal.
function popCrystal(evt, getCrystal) {
document.getElementById(getCrystal).style.float = "right";
}
If you have any questions just tag me in the post.
edit: I just realized this is hard to read... Im sorry about that. I am at work so I am not going to rewrite it but I will explain a little bit.
This is how onclick works:
onclick is an event listener that gets triggered with the DOM element is clicked. It calls a function which we called "popCrystal". popCrystal has to arguments which are event, and the id of the current div. So you see how we go from image1 to image4 along side the respective id's? That's so we can call the specific element later on.
finally we get to the javascript. This is where we actually make the "popCrystal" function. We will populate it with the same to arguments as the one in the div elements. Inside the function is where you will put your code telling it what to do. I simply used float right to show you how it selects the individual elements.
Hope that helps even though my explanation is quite sloppy.

circular linked list not working as expected (jquery)

I created a circular linked list to transverse through an ul of images (i made an image gallery and am using the linked list to go through the images with the left and right arrow keys). Everything works fine until I get to the end of the list and try to go back to the first picture (or pressing left, when i get to the beginning and try to get to the last). This is my first time using jQuery and I'm not very good with circular linked lists (i only had to use one once--for school) and it seems like the problem is the if/else statement in my getNextPic function.
BTW I know this is really sloppy. Like I said, first time, so I'm sorry if it's a little difficult to follow. I'm posting a lot of my code because I always see people on here not posting enough to find the problem. Most of this i know works fine. The problem lies in getNextPic function as I said, 3rd snippet down. Thank you to anyone who attempts to help :)
here is a fiddle
html
<div id="gallery">
<div id="main">
<img id="main_img" src="d:/allyphotos/amanda_1.jpg" alt=""/></div>
<div id="thumbnail">
<ul>
<li><img class="thumb" id="long" src="d:/allyphotos/thumb/olivia_2.jpg"/></li>
<li><img class="thumb" id="long" src="d:/allyphotos/thumb/autumn_1.jpg"/></li>
<li><img class="thumb" id="long" src="d:/allyphotos/thumb/olivia_2.jpg"/></li>
<li><img class="thumb" id="long" src="d:/allyphotos/thumb/autumn_1.jpg"/></li>
<li><img class="thumb" id="long" src="d:/allyphotos/thumb/olivia_2.jpg"/></li>
<li><img class="thumb" id="long" src="d:/allyphotos/thumb/autumn_1.jpg"/></li>
<li><img class="thumb" id="long" src="d:/allyphotos/thumb/olivia_2.jpg"/></li>
<li><img class="thumb" id="long" src="d:/allyphotos/thumb/autumn_1.jpg"/></li>
</ul>
</div>
</div>
jQuery
document ready function
$(document).ready(function(){
//these ($first and $last) dont change
var $first = $('li:first img', '#gallery ul');
var $last = $('li:last img', '#gallery ul');
//set to current selected image to be displayed
var current = $first;
var previousImage = current;
runGallery(current, $first, $last, previousImage);
});
my runGallery function
function runGallery($current, $first, $last, previousImage){
//first and last thumbnails, selected and current
$("body").keydown(function(e){
// left arrow pressed
if ((e.keyCode || e.which) == 37)
{ $current = getNextPic($current, $first, $last, false);//false gets previous img, true gets following img
fade($current, previousImage);//fade selected, unfade previously selected
previousImage=$current;
var newlink = $($current).attr('src').replace('thumb/', '');
$('#main_img').attr('src', newlink);//set $current to main_img
}
// right arrow pressed
if ((e.keyCode || e.which) == 39)
{
$current = getNextPic($current, $first, $last, true);
fade($current, previousImage);
previousImage=$current;
var newlink = $($current).attr('src').replace('thumb/', '');
$('#main_img').attr('src', newlink);
}
});
$("#gallery li img").click(function()
{
//fade selected and unfade previous selected
fade(this, previousImage);
$current = this;
previousImage = this;
//get src for clicked thumb and change to full version
var newlink = $(this).attr('src').replace('thumb/', '');
$('#main_img').attr('src', newlink);
});
var imgSwap =[];
$("gallery li img").each(function()
{
imgUrl = this.src.replace('thumb/','');
imgSwap.push(imgUrl);
});
$(imgSwap).preload();
}
my getNextPic function -- this is where I believe the problem lies. I have commented the lines that aren't working properly
function getNextPic(current, first, last, boolval)
{
var next = $(current).closest('li');
if(boolval===true)
{
if(current === last)
{
next = first;//this seems to never happen???
}
else
{
next = $(next).next('li');
next = $(next).find('img');
}
}
else
{
if(current === first)
{
next = last;//this also never happens
}
else
{
next = $(next).prev();
next = $(next).find('img');
}
}
return next;
}
my fade function, 99.999% sure this has absolutely nothing to do with the problem but posting it anyway
function fade(current, previous)
{
$(previous).fadeTo('fast',1);
$(current).fadeTo('fast', 0.5);
}
The preload function, which i did not write (i got it from a tutorial) but i know isnt contributing to the problem. Posting so anyone who looks can rule it out too.
$.fn.preload = function(){
this.each(function(){
$('<img/>')[0].src=this;
});
}
Comparison of jquery objects cannot be done directly.
Your code contains, for example
current === last
Instead, as suggested in this answer, use the inner object:
You need to compare the raw DOM elements, e.g.:
if ($(this).parent().get(0) === $('body').get(0))
or
if ($(this).parent()[0] === $('body')[0])
Check out this fixed fiddle for your expected results.

How to make an image change into others on click?

I'm trying to make a sort of a minimal clickable "slideshow". So far I have only managed to make the image change into another. but I want to add other images to it. I tried to add other ifs and elses on the javascript but it doesn't work. (I'm a noob...) How can I do it? I juts want to click and the images change. This is my code so far:
<div> <img alt="" src="1.jpg" id="imgClickAndChange" onclick="changeImage()"/> </div>
<script language="javascript">
function changeImage() {
if (document.getElementById("imgClickAndChange").src = "1.jpg")
{
document.getElementById("imgClickAndChange").src = "2.jpg";
document.getElementById("imgClickAndChange").src = "3.jpg";
}
}
</script>
thank you!
In your condition you need a double equals == - you can also pass this in to avoid getElementById multiple times. If you want to make a cycler - you can put your sources into an array and cycle thru that:
<img alt="" src="1.jpg" id="imgClickAndChange" onclick="changeImage(this)"/>
var images = ["1.jpg", "2.jpg", "3.jpg"];
function changeImage(img) {
var currentIndex = images.indexOf(img.src);
var zeroBasedLength = images.length - 1;
if (currentIndex == zeroBasedLength)
img.src = images[0];
else
img.src = images[++currentIndex];
}
If you want to cycle through those images, I'd make an array and swap the position of the elements in it like:
var imgs = ["2.jpg", "3.jpg", "1.jpg"];
function changeImage() {
document.getElementById("imgClickAndChange").src = imgs[0];
imgs.push(imgs.shift())
}
jsFiddle example

Categories