0

I'm struggling to uncover what the problem is with this jQuery code. I'm trying to move a couple of elements from one div into another. Depending on the width of the screen. The code works on page load, but not when I resize.

var domWidth = $(window).width();

//Move around page elements
function moveElements() {
    var pageTitle = $('.page-title'),
        actionAlert = $('.action-alert'),
        banner = $("#banner>.container"),
        header = $("header>.container"),
        mainContent = $(".main-content");

    if (domWidth < 1024) {
        pageTitle.prependTo(mainContent);
        actionAlert.appendTo(header);
    } else {
        pageTitle.appendTo(banner);
        actionAlert.prependTo(banner);
    } 
}

$(document).ready(function() {
    moveElements();   
    $(window).resize(function() {
        moveElements();
    });

});
TylerH
  • 20,799
  • 66
  • 75
  • 101
Dallby
  • 596
  • 4
  • 19

2 Answers2

1
 //Move around page elements
function moveElements() {
  var domWidth = $(window).width();
  var pageTitle = $('.page-title'),
    actionAlert = $('.action-alert'),
    banner = $("#banner >.container"),
    header = $("#header >.container"),
    mainContent = $(".main-content");
  if (domWidth < 1024) {
    pageTitle.prependTo(mainContent);
    actionAlert.appendTo(header);
  } else {
    pageTitle.appendTo(banner);
    actionAlert.prependTo(banner);
  } 
}

$(document).ready(function() {
moveElements();   
$(window).resize(function() {
    moveElements();
});

});

Some Serious edits are made to your code .
the errors in your code are

  1. Main one is you put var domWidth =$(window).width(); Outside the function. //it should be within the function because you need to find the width each time the function works.
  2. You missed to put a # in header = $("header>.container")

For the sake of checking I made a working demo in https://jsfiddle.net/8m0d1462/ (reduced the width to 400 for the sake of checking)

Sachin
  • 2,627
  • 1
  • 19
  • 35
0

You can trigger the event from the div change listener.

$(window).trigger('resize')

Check this to get more idea

Community
  • 1
  • 1
Zumry Mohamed
  • 9,318
  • 5
  • 46
  • 51