comfortablyNumb comfortablyNumb - 6 months ago 9
Javascript Question

Only prepend one time below a width and one time above a width

I would like to prepend a header tag to my webpage when the browser size is below 768px and remove it when it is above 768px no matter how many times I switch between the two sizes. I created the code below and it works fine if I use the sizing window but if I manually resize it then it constantly fires, causing multiple header tags.

What I would like for it to do it only fire one time if it is below 768px and one time above 768px.

At first I didn't have my code inside the resize function, but then it would only work one time so that if I increased it about 768px, the header tag disappeared but if I decreased the size again the header didn't get reapplied.

$(document).ready(function (){
$(window).on('resize', function(){
var width = $(window).width();
if (width < 768) {
insertHeader();
}
if(width > 767) {
removeHeader();
}
});
});

//Function to add header
function insertHeader() {
var headerTag = $("body").prepend(
"<header class='container container-style'> \
<div class='row'> \
<div class='col-xs-12'> \
<a href='#'><img class='img-responsive' \
src='img/dreamstime_s_52258696.jpg' alt='cartoon drawing of 1965 GTO'></a> \
</div> \
</div> \
</header>");
return headerTag
}

function removeHeader() {
var headerTag = $("header").remove();
return headerTag;
}

Answer

You just want to debounce the event, there's many ways to do this, but in this case a simple flag would suffice

$(window).data('flag', $(window).width() < 768).on('resize', function() {
    var width = $(window).width();
    var flag  = $(this).data('flag');

    if (width < 768 && flag) {
        insertHeader();
        $(this).data('flag', false);

    } else if (width > 768 && !flag) {
        removeHeader();
        $(this).data('flag', true);

    }
});

FIDDLE

Comments