wowzuzz
wowzuzz

Reputation: 1388

Make HTML element based off of document width

I'm trying to add a button for a mobile menu when the document width is less then 470.

It does it when the page loads initially, but when I mess with the width of the actual document on my browser it does not change alongside the document. How do I achieve this?

Button should appear when width is less then 470 and go away when page width is greater then 470, basically.

Here is my code.

        var width = $(document).width();
        if (width < 470) {
            $("<button id='menu'>Menu</button>").insertAfter("#navigation a img");
        } else {
            $("<button id='menu'></button>").hide();
        }

Upvotes: 0

Views: 65

Answers (2)

Anoop
Anoop

Reputation: 23208

Check width of document every time window size change.

function onresize(){
   var width = $(document).width();
   if (width < 470) {
        if($("#menu").length){
               $("#menu").show();
         }
         else{
                $("<button id='menu'>Menu</button>").insertAfter("#navigation a img");
         }
    } else {
        $("#menu").hide();
    }
}

onresize()//first call
$(window).resize(onresize);

Upvotes: 3

David Thomas
David Thomas

Reputation: 253396

Bind the function/checks to a resize method on the window:

$(window).resize(
    function(){
        /* do stuff in here */
    });

Simple proof-of-concept.

Upvotes: 3

Related Questions