I am attempting to make some css change when using mobile but an unknown variable displays as undefined.

I have searched through numerous tutorials and found lots of different solutions but I am a beginner to javascript and html and don't entirely understand them. I am using chrome and changing the user agent to see what happens on mobile.

<!DOCTYPE html>
<html>
    <body>

        <p id="demo">Show</p>

        <div id="device"></div>
        <script type="text/javascript">

            var innerHTML="";

            testExp = new RegExp('Android|webOS|iPhone|iPad|' +
                               'BlackBerry|Windows Phone|'  +
                               'Opera Mini|IEMobile|Mobile' , 
                              'i');

              if (testExp.test(navigator.userAgent))
                   document.getElementById("device").innerHTML =
                        show();
              else
                   document.getElementById("device").innerHTML = 
                        hide();

            function show() {
              document.getElementById("demo").style.display = "none";
            }

            function hide() {
              document.getElementById("demo").style.visibility = "visible";
            }


        </script>

        <p>End</p>

    </body>
</html>

On desktop it should show:

Show
End

But it displays:

Show
undefined
End

On mobile the 'show' disappeared. But undefined does not.

2 Answers

1
Hickacou On

The problem comes from this line : document.getElementById("device").innerHTML = hide(); The hide function has no return, so if you use the data it returns, as it returns nothing, it puts undefined inside #device element.

0
Community On

Thanks for your help I was a bit of a beginner so thanks for the support. For a reason I do not understand, I had to put something in a return before it could complete the function

I may not have worded the above correctly please feel free to clarify