tjcss
tjcss

Reputation: 860

$(window).resize conditional = if page is less than

I want to move an element (div) in the dom from one place to another using jQuery. I have the code working almost too well, in that it's appending my code every single time the browser is resized and then carries on until the browser crashes.

Here's my code:

$(window).resize(function() {
    var bodyWidth = $(window).width();
    if(bodyWidth < 740){
        $('.GalleryHeader').appendTo('li');
    }
});

How do I get this to only run once, so it only does the one time, and then perhaps put it back into it's original location in the dom when resizing back up over 740px.

Upvotes: 0

Views: 2027

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388416

Try

jQuery(function () {
    var flag;
    $(window).resize(function () {
        var bodyWidth = $(window).width();
        console.log(bodyWidth)
        if (flag !== false && bodyWidth < 740) {
            //move the element to new location
            console.log('less')
            flag = false;
        } else if (flag !== true && bodyWidth >= 740) {
            //put it back to original location
            console.log('more')
            flag = true;
        }
    }).resize();
})

Demo: Fiddle

Upvotes: 1

Related Questions