Raktim 0 Posted December 23, 2019 Report Share Posted December 23, 2019 This code gives an error that x[m] is undefined when it calls show(i) but it works fine if I call like show(0). What happens? I already declare x and m then why it gives an error? My code... <html> <head> <style> .myslides{margin: 0px;} </style> </head> <body> <div class="myslides"></div> <div class="myslides"></div> </body> <script> var x = document.getElementsByClassName("myslides"); var i = -1; function show(m) { x[m].style.display = "block"; } function hide(n) { x[n].style.display = "none"; } while(i<x.length) { i = i+1; show(i); setTimeout(hide(i), 3000); if(i==x.length){i = -1;} } </script> </html> Quote Link to post Share on other sites
Ingolme 1,019 Posted December 24, 2019 Report Share Posted December 24, 2019 It means that there is no element in x which has index m. You should debug the code and see which value m has when that function is called. Most likely your loop is going 1 less than the smallest index or 1 more than the largest index. It probably is better if you initialize i as 0 and put the increment operation after the rest of the code in the loop has executed. Another issue in your code is that you're calling hide(i) instantly and passing its return value to setTimeout(). Quote Link to post Share on other sites
dsonesuk 913 Posted December 24, 2019 Report Share Posted December 24, 2019 (edited) If you have two elements there index will be 0 and 1, -1 While loop : good (-1 < 2) 0 : good If : ignore While loop :good (0 < 2) 1 : good If : Ignore While loop : good (1 < 2) 2 : bad no index for third element, undefined If : change to -1 If condition should check value after increment takes place and before show()/ hide(); and reset to 0 not -1 console.log shows error when i equals 2 0 1 2 Uncaught TypeError: Cannot read property 'style' of undefined at show (<anonymous>:8:22) at <anonymous>:19:17 Edited December 24, 2019 by dsonesuk Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.