Search code examples
javascripthtmlviewport

meta viewport tag script not working


I'm trying to use the solution provided here Meta viewport ONLY for phones? to generate a meta viewport tag on phones only, I'm adding the script in the head section of the document but it's not being generated, and I'm getting a "SyntaxError: Expected token ')' error on the console.

Here's the script I'm using:

<script type="text/javascript">
    $(document).ready(function(){
        if(navigator.userAgent.match(/Android/i)
            || navigator.userAgent.match(/webOS/i)
            || navigator.userAgent.match(/iPhone/i)
            || navigator.userAgent.match(/iPod/i)
            || navigator.userAgent.match(/BlackBerry/i)
            || navigator.userAgent.match(/Windows Phone/i)) {
            document.write('<meta name='viewport' content='width=device-width, user-scalable=no'>');
        }
    });
</script>

Solution

  • Just fix this one line:

    document.write("<meta name='viewport' content='width=device-width, user-scalable=no'>");
    

    You need to swap the opening and closing ' for ", otherwise the string can't be properly parsed.

    Complete code:

    <script type="text/javascript">
        $(document).ready(function(){
            if(navigator.userAgent.match(/Android/i)
                || navigator.userAgent.match(/webOS/i)
                || navigator.userAgent.match(/iPhone/i)
                || navigator.userAgent.match(/iPod/i)
                || navigator.userAgent.match(/BlackBerry/i)
                || navigator.userAgent.match(/Windows Phone/i)) {
                document.write("<meta name='viewport' content='width=device-width, user-scalable=no'>");
            }
        });
    </script>