JavaScript Click images with button navigation - javascript

New to web development and trying to create a gallery of images that cycle through with the click of a "previous" and "next" button. Does anybody know how to do this? I don't think I've done anything right but I'll include what I've done so far. The idea is to make this adaptable to n indefinite number of images.
code:
<img src= "photos/1.jpg" id="currentImage" height="288"/>
<button id= "prev" onclick="prevImage()" class="portfolioNavigation">Previous</button>
<button id= "next" onclick="nextImage()" class="portfolioNavigation">Next</button>
<script type= "text/javascript">
var counter = 2;
var 1 = "photos/1.jpg";
var 2 = "photos/2.jpg";
var 3 = "photos/3.jpg";
prev.onclick = function(){
document.getElementById("currentImage").src = counter - 1;
counter--;
}
next.onclick = function(){
document.getElementById("currentImage").src = counter + 1;
counter++;
}
if(counter == 3){
counter = 0;
};
</script>

There is no need of using "onclick" inside button tags.
<script type= "text/javascript">
var counter = 2;
var sourceUrl = "photos/" + counter + ".jpg";
var prev = document.getElementById("prev");
var next = document.getElementById("next");
prev.onclick = function(){
counter--;
document.getElementById("currentImage").src = sourceUrl;
}
next.onclick = function(){
counter++;
document.getElementById("currentImage").src = sourceUrl; }
if(counter == 3){
counter = 0;
};
</script>

As others have posted, you cannot use an int as a variable name.
You also had "onclick" events on each button and events set via jQuery, you just need one or the other.
Storing each src string in an array and accessing it by using "counter" will work for you. It will also allow you to use a variable amount of images.
HTML
<img src= "photos/1.jpg" id="currentImage" height="288"/>
<button id= "prev" class="portfolioNavigation">Previous</button>
<button id= "next" class="portfolioNavigation">Next</button>
JavaScript
var counter = 0;
var srcArray = ["photos/1.jpg", "photos/2.jpg", "photos/3.jpg"];
prev.onclick = function(){
document.getElementById("currentImage").src = srcArray[--counter];
}
next.onclick = function(){
document.getElementById("currentImage").src = srcArray[++counter];
}
if(counter == 3){
counter = 0;
};
If you inspect the image element in this JSFiddle, you'll see the src updating correctly.

There are couple of issues in your code right now. One of them is that your variables names are plain numbers. You cannot have variable names starting with numbers in JavaScript. Although not a great example, _1 is valid, image1 is a valid and even a more descriptive variable number.
Another issue is, when you are setting the src attribute of currentImage you are also setting that attribute to a value of plain number. That is not a valid image url.
You can put the photo URLs in an array and cycle through those images when next and previous buttons are pressed.
Try something like this (warning untested code):
var images = ["photos/1.jpg", "photos/2.jpg", "photos/3.jpg"];
var numImages = images.length;
prev.onclick = function(){
document.getElementById("currentImage").src = images[(counter - 1) % numImages];
counter--;
}
The significance of the % operator here is that it wraps around the value of [0, numImages).

Related

How to make images appear randomly in Javascript?

I need to create a web page with a button that says "start game". When this button is clicked, 5 images I have downloaded (img1.png...img5.png) must appear randomly, one at a time, every half a second. Here is my code so far, any help would be greatly appreciated!
<html>
<head>
<script>
var rollImagesSchedule;
var rollImagesCounter;
function rollImagesAnimation(){
rollImagesCounter = 0;
rollImagesSchedule = setInterval(500);
}
function rollImages(){
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
rollImagesCounter = rollImagesCounter + 1;
if (rollImagesCounter == 10){
clearInterval(rollImagesSchedule);
}
}
</script>
</head>
<body>
<h1>Game</h1>
<button onClick="rollImagesAnimation()">Start frog game</button>
<br /><br />
<img id="display" style='width:200px; height:200px;'>
</body>
</html>
I think you're getting stuck with the way to use setInterval.
You can try to create a counter outside setInterval function, and nest all of your works inside of it. And the counter should be checked at the top.
function rollImages(){
var counter = 0;
var interval = setInterval(function () {
if (counter === 10) {
clearInterval(interval);
return;
}
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
counter++;
}, 500);
}
Then, you can edit the way to catch event rollImages:
<button onClick="rollImages()">Start frog game</button>
My English is not very good, so I might misunderstand your question. Let me answer it according to what I understand.
Your requirement is to randomly display one of the five pictures every 500 milliseconds, right? If so, you can try this idea:
Put the src of 5 pictures into an array
var imageSrcs = ["image1","image2","image3","image4","image5"];
Every 500 milliseconds, execute the following function:
function rollImages(){
// Randomly generate a random number between 0-4
int index = Math.floor(Math.random() * 5) + 1;
var theImage = document.getElementById("display");
// Use random numbers as subscripts and take values from the array
theImage.src = imageSrcs[index];
}
You can store the images name files into an array and then setInterval a random number and assign the source of an img html element:
var list = [
"image1.jpg",
"image2.jpg",
"image3.jpg",
];
var i = 0;
function changeImgs() {
var imageValue = Math.floor(Math.random() * list.length - 1) + 1;
image.src = list[imageValue];
}
setInterval(function() {
changeImgs()
}, 2000);
window.onload = changeImgs;
<img id="image" class="size">

How do I change the image src in my slider?

I have this image for a slider. I want it to fade to the next image after the button is clicked. The JQuery makes the image fade in and out to make the transition cleaner when the src changes. However, the image stays the same after fading.
Html
<button onclick = "prev()" id = "prev">Prev</button>
<img id = "slider" src = "" height = "600px" width = "600px"/>
<button onclick = "next()" id = "next">Next</button>
JQuery
var images = ['', '', ''];
var num = 0;
function next() {
var slider = $('#slider');
num++;
if(num >= images.length) {
num = 0;
}
slider.fadeOut('slow', function() {
slider.src = images[num];
slider.fadeIn('slow');
});
}
function prev() {
var slider = $('#slider');
num--;
if(num < 0) {
num = images.length-1;
}
slider.fadeOut('slow', function() {
slider.src = images[num];
slider.fadeIn('slow');
});
}
I have taken out the images I tested it with as their links were too long. The three slider images would be in the JQuery "images" variable and the starting one in the image src.
Assuming that images is an array of image URLs, then your mistake is trying to set slider.src instead of slider.attr('src, value);.
So, use this instead:
slider.attr('src', images[num]);

Creating a counter

I'm creating a counter and I'm having a hard time making it.
The goal of the counter is that for ever second passed a number will increase by 170.
As you can see below the number does not add up and is made on a new line, mostly because I dont know how to make it add up. Some thing like this clock from The Economist
<!DOCTYPE html>
<html>
<body>
<p>Click the button see how much AirHelps market increases by every second.</p>
<button onclick="counterFunction()">See it now</button>
<p id="counter"></p>
<script>
function counterFunction() {
setTimeout(function () {
var text = "";
var i = 170;
while (i < 3500) {
text += "<br>The number is " + i;
i+=170;
}, 1000) }
document.getElementById("counter").innerHTML = text;
}
</script>
</body>
</html>
Any ideas on how I can make this and what is wrong with my code?
Don't use inline JavaScript (JavaScript inside HTML element attributes), it is horrible for maintainability and readability.
You seem to have a misconception about how timeouts, intervals and while loops work, what you want is an interval.
Define a count variable outside of the event listener function, then on each iteration of the interval increment the count variable by one and multiply that number by 170.
I added a little bit in there to hide the button once it has been clicked, just to stop the user from restarting the counter.
var clicker = document.getElementById('clicker');
var counter = document.getElementById('counter');
var count = 0;
clicker.onclick = function() {
setInterval(function () {
counter.textContent = "The number is " + ++count * 170;
}, 1000);
clicker.style.display = 'none';
}
<p>Click the button see how much AirHelps market increases by every second.</p>
<button id="clicker">See it now</button>
<p id="counter"></p>
http://jsfiddle.net/mblenton/Le4vxzrn/2/
function counterFunction() {
var text = ""; var i = 170; var delay = 0; var k = 1;
while (i < 3500) {
text = "The number is " + i;
i += 170;
delay = k * 1000;
doSetTimeout(text, delay);
k++;
}
}
function doSetTimeout(text, delay) {
setTimeout(function () {
document.getElementById("counter").textContent = text;
}, delay);
}
You need to use setInterval, not setTimeout`. Note that if you click the button, it will reset your timer.
You also need to declare var i and var text outside the scope of the Interval, or they will also be reset each iteration.
There were a few things wrong with your code. Among other things:
your i variable was declared in the wrong place to be reused
your closing braces were in the wrong place for the callback function
you were using a while loop, which runs synchronously, whereas you really want to just use a setInterval call.
This should work:
function counterFunction() {
var i = 170;
var text = "";
var interval = setInterval(function () {
text += "<br>The number is " + i;
i+=170;
document.getElementById("counter").innerHTML = text;
if (i >= 3500) {
clearInterval(interval);
}
}, 1000);
}
<p>Click the button see how much AirHelps market increases by every second.</p>
<button onclick="counterFunction()">See it now</button>
<p id="counter"></p>
Ok so the adder variable should be declared outside of the timeout function, because if not you are replacing the value. and you should use setInterval
var p =0;
function counterFunction(){
setInterval(function(){ p+=170;
console.log('value of p '+p);
}, 3000);
}
if you dont want to roll your own here is a nice counter
http://keith-wood.name/countdown.html

Update counter in slider

I have a slider that I've built myself, which is a carousel that infinitely loops. I'm wanting to create a counter (1 of 4, 2 of 4) etc, with the last number being the total number of slides present and the 1/2/3/4 displays which slide you are viewing.
This is what I have so far for my counter:
var $tota = $('.past-project-container').find('span.total');
var $curr = $('.past-project-container').find('span.current');
function changeCurr(){
$tota.text(numberOfProjects);
$curr.text(1);
}
changeCurr();
HTML:
<span class="slide-count-container">
<span class="current">1</span> of <span class="total">1</span>
</span>
And this is my JS for the carousel if it helps
var $carousel = $('.past-project-slider'), carW = $carousel.outerWidth(), intv;
$carousel.wrapInner('<div id="slider" />');
var $slider = $('#slider');
numberOfProjects = $('.past-project-each').length;
$slider.css({position:'absolute',left:0, width:carW*numberOfProjects}).find('.past-project-each').css({'float':'left'});
function move(cb){
if(!$slider.is(':animated')){
if(cb=='next'){
$slider.animate({left:-carW},800,function(){
$slider.append($('.past-project-each:first'));
$slider.css({left:0});
});
}else{
$slider.prepend($('.past-project-each:last'));
$slider.css({left:-carW});
$slider.animate({left:0},800);
}
}
}
$('#next-past-project, #prev-past-project').click(function(){
var btn = this.id=='next-past-project' ? move('next') : move('prev');
});
Many thanks,
R
Rather than constantly reading and converting the contents of the $curr element its probably better to keep track in another variable, like so:
var $tota = $('.past-project-container').find('span.total');
var $curr = $('.past-project-container').find('span.current');
var currentIndex = 0;
function changeCurr(){
$tota.text(numberOfProjects);
// If we've not reached the final index, add one, else return to the start
currentIndex = (currentIndex == numberOfProjects) ? 1 : currentIndex + 1;
$curr.text(currentIndex);
}
changeCurr();
This will count up until the last slide. Be sure to call changeCurr() on each slide transition.

With only one button to scroll through images, how do I make a permutation?

I am writing this in JavaScript, and the issue is that I can't seem to figure out how to make a permutation. Ideally, I want to click the button and image would change to next, from a1.jpg to a2.jpg to a3.jpg to a4.jpg to a1.jpg and so on... But when I wrote this code, it would skip a2 and a3. I also did rearrange the conditionals since I realized that it reads from the top to bottom, but it would always skip one of the four pictures.
function changeImage() {
if (document.images) {
if (document["buttonOne"].src == a3.src){
document["buttonOne"].src = a4.src}
}
if (document.images) {
if (document["buttonOne"].src == a2.src){
document["buttonOne"].src = a3.src
}
if (document.images) {
if (document["buttonOne"].src == a1.src){
document["buttonOne"].src = a2.src}
}
if (document.images) {
if (document["buttonOne"].src == a4.src){
document["buttonOne"].src = a1.src}
}
}
Try it in a more simple way
var imgs = ['a1.jpg', 'a2.jpg', 'a3.jpg', 'a4.jpg'];
function changeImage() {
var img = document["buttonOne"];
if (!img._index) img._index = 0;
img.src = imgs[img._index++];
if (img._index >= imgs.length) img._index = 0;
}
img._index replaces the global variable with index of the shown image. Good to use when you want to change a few images, each of them will keep its own counter.
ps: if the only thing that changes is the number in the filename then the code can be even shorter without an array:
function changeImage(max) {
var img = document["buttonOne"];
if (!img._index) img._index = 0;
img.src = 'a' + img._index + '.jpg';
if (img._index >= max) img._index = 0;
}

Categories