Jump to content
Raktim

JS error

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>

 

Share this post


Link to post
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().

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...