Jump to content

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

            .myslides{margin: 0px;}
        <div class="myslides"></div>
        <div class="myslides"></div>
            var x = document.getElementsByClassName("myslides");
            var i = -1;
            function show(m)
                x[m].style.display = "block";
            function hide(n)
                x[n].style.display = "none";
                i = i+1;
                setTimeout(hide(i), 3000);
                if(i==x.length){i = -1;}


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

Link to post
Share on other sites

If you have two elements there index will be 0 and 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

Uncaught TypeError: Cannot read property 'style' of undefined
    at show (<anonymous>:8:22)
    at <anonymous>:19:17


Edited by dsonesuk
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.

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.

  • Create New...