Search code examples
jquerymedia-queriesaddition

jQuery - Add element once the screen width is below 500px


I would like to add an element to the body once the width of the screen is below 500px. I used the code below but the element does not appear. Hopefully somebody is able to help me out?

$(window).resize(function(){
if ($(window).width() <= 500){  
  $("body").append("<a href="#">Home</a>");
} });

Solution

  • $(window).resize(function(){
        if ($(window).width() <= 500){  
            $("body").append("<a href='#'>Home</a>");
        }
    });
    

    Notice the single quotes around the hash tag (your code should now work).

    If you want to use double-quotes inside a double-quoted string, your other option is to escape them, as such:

    "<a href=\"#\">Home</a>"
    

    Notice the backwards slashes? That escapes a special character. This method should work for you as well. Same works the opposite way. So, to conclude, all of these will work:

    "<a href=\"#\">Home</a>"
    
    "<a href='#'>Home</a>"
    
    '<a href=\'#\'>Home</a>'
    
    '<a href="#">Home</a>'
    

    See this article, jQuery API Documentation: String Quoting, for more information.

    IMPORTANT

    If the user resizes their browser, say, 3 times, then your script will end up appending 3 different anchor elements, which I don't think is what you are wanting.

    So, what you may consider doing is simply putting your link INSIDE the HTML page itself, and then using CSS to hide it. Then, when the user goes below 500px, you can show the element, and when the user goes above 500px, you can hide it again, like so:

    HTML:

    <!--- everything else in the Body -->
    <a class="hidden-link" href="#">Home</a>
    

    CSS:

    .hidden-link {
        display: none;
    }
    

    jQuery:

    $(window).resize(function(){
        if ($(window).width() <= 500) {  
            $('.hidden-link').show();
        } else {
            $('.hidden-link').hide();
        }
    });
    

    Also, just as a side note, since I have not seen the rest of your code, ensure that you are putting everything inside $(function() { }); (if you haven't already), which executes everything once the browser has had a chance to parse all the HTML into the DOM.

    CSS-only method

    You could simply use media-queries, if you like:

    .hidden-link {
        display: none;
    } 
    
    @media only screen 
    and (max-width : 500px) {
    
        .hidden-link {
            display: inline;
        }
    
    }