Jump to content

JS error


Raktim

Recommended Posts

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>

 

Link to comment
Share on other sites

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().

Link to comment
Share on other sites

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 by dsonesuk
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...