Question from JavaScript image slider. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Question from JavaScript image slider.

Code is inserted below. Why there is so much of lag while click on the prev button ? What are the errors in the code.. Can anybody answer me. https://code.sololearn.com/W5QijUn3LIoO/?ref=app

12th Jun 2020, 10:47 AM
Ajitha G R
Ajitha G R - avatar
8 Answers
+ 4
I did some modifications to your code ,not sure if you wanted this way but here it is var num = 0; var x=document.getElementById("btn1"); var y="click"; btn1.addEventListener(y,next); function next() { var slider = document.getElementById('slider'); num++; if(num < images.length) { slider.src = images[num]; } else{ num=0; slider.src=images[num]; } } var a =document.getElementById("btn2"); var b="click"; btn2.addEventListener(b,prev); function prev() { var slider = document.getElementById('slider'); num--; if(num >=0) { slider.src=images[num]; } else { num=2; slider.src=images[num]; } } }
12th Jun 2020, 11:26 AM
Abhay
Abhay - avatar
+ 2
Ajitha G R it's working fine with every image showing up
12th Jun 2020, 12:07 PM
Abhay
Abhay - avatar
+ 2
First image is at 0 index when you click next index is still 0 ,so nothing happens and later n becomes 1
12th Jun 2020, 2:52 PM
Abhay
Abhay - avatar
+ 1
you should num-- in prev() and check if num becomes smaller than 0 https://code.sololearn.com/WsG7OrVX5P81/?ref=app
12th Jun 2020, 11:00 AM
Gordon
Gordon - avatar
+ 1
Abhay .sry, Yes it is working...Thank you๐Ÿ‘๐Ÿ‘
12th Jun 2020, 12:11 PM
Ajitha G R
Ajitha G R - avatar
+ 1
Abhay In function next(), n++ is placed before the if statement, So n=1, o/p will be, slider.src=images[1];it is not starting from 0,though it is correct and giving proper result. If I placed n++ inside the if statement like this๐Ÿ‘‡, If(num<images.length){ slider.src=images[num];. // images[0] num++; } I need to click twice to slide the first image.why? what is the reason?
12th Jun 2020, 1:59 PM
Ajitha G R
Ajitha G R - avatar
+ 1
OK..Got it
12th Jun 2020, 2:58 PM
Ajitha G R
Ajitha G R - avatar
0
Gordon Thank you for replying.๐Ÿ˜Š but I used slightly different logic than what is already given in lesson.i checked your code ,it is not working.
12th Jun 2020, 11:09 AM
Ajitha G R
Ajitha G R - avatar