Back/Forward button between 3 images - javascript

I am trying to make a function that can go forward and backwards between 3 images, depending on which button is pressed.
So for now I have made a function for forward and backwards button:
Updated code:
var img1 = "images2/page1.jpg";
var img2 = "images2/page2.jpg";
var img3 = "images2/page3.jpg";
function back() {
var page = document.getElementById("page_1");
if (page.src == img3) {
page.src = img2;
} else if (page.src == img2) {
page.src = img1;
} return page.src;
}
function forward() {
var page = document.getElementById("page_1");
if (page.src == img1) {
page.src = img2;
} else if (page.src == img2) {
page.src = img3;
} return page;
}
But when I run it in my HTML document, the buttons do nothing.
HTML:
<script src="indiv.js"></script>
<img id="page_1" src="images2/page1.jpg" height="400"><br />
<button type="button" onclick="back()">Last page</button>
<button type="button" onclick="forward()">Next page</button>
What am I missing?
Thank you from the newbie.

Check this code:
var img1 = "https://www.illumina.com/content/dam/illumina-marketing/images/company/featured-articles/bottlenose_dolphin.png"
var img2 = "https://i.pinimg.com/564x/65/d6/cf/65d6cfcb2bb5193d6d160157b34b2bd0.jpg"
var img3 = "https://i.pinimg.com/originals/d6/98/88/d698888c81f296032bd595f758b76dc5.jpg"
function back() {
var page = document.getElementById("page_1");
if (page.src == img3) {
page.src = img2;
} else if (page.src == img2) {
page.src = img1;
} else if (page.src == img1) {
page.src = img3;
}
}
function forward() {
var page = document.getElementById("page_1");
if (page.src == img1) {
page.src = img2;
}else if (page.src == img2) {
page.src = img3;
}else if (page.src == img3) {
page.src = img1;
}
}
<img id = "page_1" src = "https://www.illumina.com/content/dam/illumina-marketing/images/company/featured-articles/bottlenose_dolphin.png" height = "200"><br>
<button type="button" onclick="back()">Last Page</button>
<button type="button" onclick="forward()">Next page</button>

The cleanest way to do this is to maintain an array of images you want to cycle through. Then have a index variable to keep track of which image to show currently. Forward and backward buttons just increase or decrease the index variable by one.
<div>
<img id="page_1" src="" height="400">
<button type="button" onclick="back()">Last page</button>
<button type="button" onclick="forward()">Next page</button>
</div>
<script>
//array of images
let map = ["https://www.hindustantimes.com/rf/image_size_444x250/HT/p2/2020/05/21/Pictures/_037138a2-9b47-11ea-a010-c71373fc244b.jpg",
"https://images.unsplash.com/photo-1494548162494-384bba4ab999?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80",
"https://image.shutterstock.com/image-photo/bright-spring-view-cameo-island-260nw-1048185397.jpg"
]
//index variable initially set to first image
let index = 0;
document.getElementById("page_1").src = map[index];
//forward button logic
function forward() {
index = (index + 1) % 3;
document.getElementById("page_1").src = map[index];
}
//backward button logic
function back() {
index = (index - 1 < 0) ? 2 : index - 1;
document.getElementById("page_1").src = map[index];
}
</script>
Codepen

Related

How to stop a setInterval function on click, and restart after a few seconds

I have an issue in my custom slider: I want to stop a setInterval event on click of the next/back buttons, and restart after 3 seconds.
The slider: http://karanbhilware.com/mail_send/slider.html
The interval code follows.
HTML:
<div class="slider">
<div id="sliderUL"> <img src="images/1.jpg" /> <img src="images/2.jpg" /> <img src="images/3.jpg" /> <img src="images/4.jpg" /> <img src="images/5.jpg" /> </div>
</div>
<div style="clear:both"> </div>
<div id="sliderNav">
<button id="back" data-file="previous" style="float:left; margin-left:50px;">previous</button>
<button id="next" data-file="next" style="float:right; margin-right:50px;">Next</button>
</div>
JavaScript:
var sliderWrap = $('#sliderUL'),
img = $('#sliderUL img')
singleWidth = sliderWrap.find('img:first-child').width(),
imageLenght = img.length,
idCount = 1,
current = 1,
firstImage = img.first();
lastImage = img.last(),
secondLast = imageLenght-1;
secondImage = img.eq(1);
firstImage.addClass('active');
img.each(function(){
$(this).attr('id','slider_'+idCount++);
});
if(current === 1){
$('#back').addClass('none');
}
$('#next').on('click',nextFun);
$('#back').on('click',backFun);
function backFun(){
if(current === imageLenght){
$('#next').removeClass('none');
}
if(current === 2){
$(this).addClass('none');
}
var backNextSlider = sliderWrap.find('img[id="slider_'+(current-1)+'"]').addClass('active').removeClass('Subactive');
sliderWrap.find('img[id="slider_'+(current)+'"]').removeClass('Subactive').addClass('backActive').removeClass('active');
current--;
}
function nextFun(){
var currentNextSlider = sliderWrap.find('img[id="slider_'+(current+1)+'"]').addClass('active').removeClass('backActive');
sliderWrap.find('img[id="slider_'+(current)+'"]').addClass('Subactive').removeClass('backActive, active');
current++;
if(current === 2){
$('#back').removeClass('none');
}
if(current === imageLenght){
$('#next').addClass('none');
}
}
var mode = 'Next';
function autRotatae(){
if(current == imageLenght)
mode = 'Back';
if(current == 1)
mode = 'Next';
if(mode == 'Next')
{
nextFun();
}
else
backFun();
}
$(document).ready(function(){
setInterval(autRotatae,2000);
})
You can't "pause" an interval. You can cancel and restart it.
Move interval creation and pausing to separate functions, so you don't repeat yourself:
var rotateInt = null;
$(document).ready(function(){
startRotate();
})
function startRotate() {
if (! rotateInt)
rotateInt = setInterval(autRotatae, 2000);
}
function pauseRotate() {
if (rotateInt)
{
clearInterval( rotateInt );
rotateInt = null;
setTimeout( startRotate, 3000 );
}
}
then, in your next/prev button handlers:
pauseRotate();
var timer;
var sliderWrap = $('#sliderUL'),
img = $('#sliderUL img')
singleWidth = sliderWrap.find('img:first-child').width(),
imageLenght = img.length,
idCount = 1,
current = 1,
firstImage = img.first();
lastImage = img.last(),
secondLast = imageLenght-1;
secondImage = img.eq(1);
firstImage.addClass('active');
img.each(function(){
$(this).attr('id','slider_'+idCount++);
});
if(current === 1){
$('#back').addClass('none');
}
$('#next').on('click',nextFun);
$('#back').on('click',backFun);
function backFun(){
clearInterval(timer);
setTimeout(function(){ timer = setInterval(autRotatae,2000);},3000);
if(current === imageLenght){
$('#next').removeClass('none');
}
if(current === 2){
$(this).addClass('none');
}
var backNextSlider = sliderWrap.find('img[id="slider_'+(current-1)+'"]').addClass('active').removeClass('Subactive');
sliderWrap.find('img[id="slider_'+(current)+'"]').removeClass('Subactive').addClass('backActive').removeClass('active');
current--;
}
function nextFun(){
clearInterval(timer);
setTimeout(function(){ timer = setInterval(autRotatae,2000); },3000);
var currentNextSlider = sliderWrap.find('img[id="slider_'+(current+1)+'"]').addClass('active').removeClass('backActive');
sliderWrap.find('img[id="slider_'+(current)+'"]').addClass('Subactive').removeClass('backActive, active');
current++;
if(current === 2){
$('#back').removeClass('none');
}
if(current === imageLenght){
$('#next').addClass('none');
}
}
var mode = 'Next';
function autRotatae(){
if(current == imageLenght)
mode = 'Back';
if(current == 1)
mode = 'Next';
if(mode == 'Next')
{
nextFun();
}
else
backFun();
}
$(document).ready(function(){
timer = setInterval(autRotatae,2000);
})

.JS Function will continue executing, with wrong values

As you can see this is actually a simple application, however the code seems to continue using the first IF statement even though it isn't correct/relevant anymore.
HTML
<div id="Slideshow">
<img id="Slide" src="images/Slide01.jpg" width="600px" height="450px">
<button type="button" onClick="SlideShowTimer()">Click Me!</button>
</div>
<!--Closing Slideshow-->
JS
function SlideShowTimer() {
var IMG1 = "images/Slide01.jpg";
var IMG2 = "images/Slide02.jpg";
var IMG3 = "images/Slide03.jpg";
var Slide = document.getElementById('Slide').src;
if (document.Slide === document.IMG1) {
document.getElementById('Slide').src = "images/Slide02.jpg"; * * * //keeps executing this even once the value has actually changed to the value of 'IMG2'***
} else if (document.Slide === document.IMG2) {
document.getElementById('Slide').src = "images/Slide03.jpg";
} else if (document.Slide === document.IMG3) {
document.getElementById('Slide').src = "images/Slide01.jpg";
} else {
alert("Something Went Wrong");
}
}
It's because
document.getElementById('Slide').src
returns an absolute path.
EDIT:
function SlideShowTimer() {
var IMG1 = "images/Slide01.jpg";
var IMG2 = "images/Slide02.jpg";
var IMG3 = "images/Slide03.jpg";
var Slide = document.getElementById('Slide');
if (Slide.src.indexOf(IMG1) >= 0) {
Slide.src = "images/Slide02.jpg";
alert('1');
} else if (Slide.src.indexOf(IMG2) >= 0) {
Slide.src = "images/Slide03.jpg";
alert('2');
} else if (Slide.src.indexOf(IMG3) >= 0) {
alert('3');
Slide.src = "images/Slide01.jpg";
} else {
alert("Something Went Wrong");
}
}
Try like this
if (Slide == IMG1) {
document.getElementById('Slide').src = IMG2;
} else if (Slide == IMG2) {
document.getElementById('Slide').src = IMG3;
} else if (Slide == IMG3) {
document.getElementById('Slide').src = IMG1;
} else {
alert("Something Went Wrong");
}

Calling function from div and link not working

I have the code below. It works on a mobile device but for some reason, that baffles me, it won't work in a desktop browser. Any ideas?
<div class="top_nav_option_wrapper"
onclick="javascript:changePage('{{ shop.url }}{{ link.url }}','fade');">
<a href="#"
onclick="javascript:changePage('{{ shop.url }}{{ link.url }}','fade');"
class="top_nav_option">{{ link.title }}</a><br>
</div>
Function
// Function used to transition a page out and navigate to a new page
function changePage(goToUrl, type, id) {
alert('HEY');
if (type == 'collection_flicker') {
prodElements = ['prod1', 'prod2', 'prod3', 'prod4'];
for (i = 0; i < prodElements.length; i++) {
if (document.getElementById(prodElements[i]) != null && document.getElementById(prodElements[i]) != document.getElementById(id)) {
document.getElementById(prodElements[i]).style.opacity = "0";
document.getElementById(prodElements[i]).style.display = "none";
}
}
flickerEffect('collection_exit', 15, 50);
window.setTimeout(function () {
window.location.href = goToUrl
}, 1000);
} else if (type == 'fade' && currentTemplate == 'collection') {
document.getElementById('watermark').style.transition = '1s opacity';
document.getElementById('watermark').style.opacity = '0';
document.getElementById('productCollectionList').style.transition = '1s opacity';
document.getElementById('productCollectionList').style.opacity = '0';
window.setTimeout(function () {
window.location.href = goToUrl
}, 500);
} else {
window.location.href = goToUrl;
}
}
I suggest the following changes - I am not sure how link.url becomes a type but you will see the idea
HTML:
<div class="top_nav_option_wrapper">
<a href="{{ shop.url }}"
onclick="return changePage(this.href,'{{ link.url }}','fade');"
class="top_nav_option">{{ link.title }}</a><br>
</div>
Script
// Function used to transition a page out and navigate to a new page
function changePage(goToUrl, type, id) {
if (type == 'collection_flicker') {
prodElements = ['prod1', 'prod2', 'prod3', 'prod4'];
for (var i = 0; i < prodElements.length; i++) {
var prodelem = document.getElementById(prodElements[i]);
if (prodelem != null && prodelem != document.getElementById(id)) {
prodelem.style.opacity = "0";
prodelem.style.display = "none";
}
}
flickerEffect('collection_exit', 15, 50);
window.setTimeout(function () {
window.location.href = goToUrl
}, 1000);
return false; // cancel link
} else if (type == 'fade' && currentTemplate == 'collection') {
document.getElementById('watermark').style.transition = '1s opacity';
document.getElementById('watermark').style.opacity = '0';
document.getElementById('productCollectionList').style.transition = '1s opacity';
document.getElementById('productCollectionList').style.opacity = '0';
window.setTimeout(function () {
window.location.href = goToUrl
}, 500);
return false; // cancel link
}
return true; // allow link
}

I need a button NOT to disapear

I am making a javascript code that has a button and when I click on it, it displays one of 5 symbols but when I click the button, it shows the random symbol but the button disapears. I'm new to javascript so can I please get some help?
<script>
function slots()
{
var slot1 = Math.floor(Math.random()*5);
if (slot1 == 0) {
document.write("\u2663");
}
if (slot1 == 1) {
document.write("\u2665");
}
if (slot1 == 2) {
document.write("\u2666");
}
if (slot1 == 3) {
document.write("\u2660");
}
if (slot1 == 4) {
document.write("7");
}
}
</script>
<button type="button" value="Spin" name="SPIN"onClick="slots(); return false;"></button>
When you write document.write() the screen refreshes, so I guess you could do something like this:
<script>
function slots()
{
var slot1 = Math.floor(Math.random()*5);
if (slot1 == 0) {
document.getElementById('value').innerHTML = "\u2663";
}
if (slot1 == 1) {
document.getElementById('value').innerHTML = "\u2665";
}
if (slot1 == 2) {
document.getElementById('value').innerHTML = "\u2666";
}
if (slot1 == 3) {
document.getElementById('value').innerHTML = "\u2660";
}
if (slot1 == 4) {
document.getElementById('value').innerHTML = "7";
}
}
</script>
<button type="button" value="Spin" name="SPIN" onClick="slots();">Click</button>
<span id="value"></span>
Slightly optimized version of otrebla's code, see it in action:
function slots() {
var slot1 = Math.floor(Math.random() * 5);
var value = document.getElementById('value');
switch (slot1) {
case 0:
value.innerHTML = "\u2663";
break;
case 1:
value.innerHTML = "\u2665";
break;
case 2:
value.innerHTML = "\u2666";
break;
case 3:
value.innerHTML = "\u2660";
break;
case 4:
value.innerHTML = "7";
break;
}
}
<button type="button" value="Spin" name="SPIN" onClick="slots();">Click</button>
<span id="value"></span>

Javascript not working in Grails

I have a simple script works fine in html. Yet in a gsp, it doesn't work anymore.
My script is very simple, as below:
// program variables
var displayElement;
// constants
var maxLength = 300;
// calculator variables
var text;
var currentLength;
var dotPosition;
var lastNumber;
var currentNumber;
var rememberedNumber;
var operator;
alert('hello22');
function parseNumber(number) {
if ((number == -1) && (dotPosition > 0) || (maxLength == currentLength)) return;
if (currentLength == 0) text = '';
currentLength++;
if (number == -1) {
text += '.';
dotPosition = currentLength;
} else text += number;
displayElement.value = text;
}
function parseBackspace() {
if (currentLength == 0) return;
if ('.' == text[currentLength-1]) dotPosition = 0;
text = text.slice(0, currentLength-1);
if(--currentLength == 0) text = '';
displayElement.value = text;
}
function parseClearEntry() {
currentLength = 0;
text = '0';
dotPosition = 0;
displayElement.value = text;
}
function parseClear() {
parseClearEntry();
lastNumber = 0;
operator = '';
//added by Kevin
displayElement.value = '';
}
function initAll() {
alert('hello1113333333');
text = '0';
currentNumber = 0;
currentLength = 0;
displayElement = document.getElementById('TextBox');
rememberedNumber = 0;
lastNumber = 0;
dotPosition = 0;
alert('hello1111111111');
}
When I included into the gsp view page, I put <g:javascript src="getKey.js" /> between the <head></head>.
Then I call the function initAll() like <body onload="initAll()">, and others like <div class="holder"><input type="button" class="buttonstyle" value="7" name="Seven" onclick="parseNumber(7)" /></div>
Can anyone tell me what's wrong? I am sure the script has been included correctly because the alert "hello22" was threw.
Try to put somewhere following code at the footer:
<g:script>
(function() { initAll(); })();
</g:script>
or
<g:script>
window.onload = initAll; //note that is's without braces
</g:script>
instead of <body onload="initAll"

Categories

Resources