Reputation: 1388
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
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
Reputation: 253396
Bind the function/checks to a resize
method on the window:
$(window).resize(
function(){
/* do stuff in here */
});
Upvotes: 3