Question

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.

Était-ce utile?

La solution

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top