0

I am trying to change the order of the divs using JavaScript`. Is this how I can go about it?

<div id="pageWrapper">
    <div id="one">1</div>
    <div id="two">2</div>
    <div id="three">3</div>
    <div id="four">4</div>
</div>

$(document).ready(function(){ 
        $('#pageWrapper').prepend('#three');
        $('#pageWrapper').prepend('#four');

});
4
  • Well does it work? Have you tried running the code? Commented Mar 8, 2014 at 0:09
  • You should consider using CSS flexbox to achieve this instead. Commented Mar 8, 2014 at 0:09
  • why would i get a -1 this is a pretty straight forward question, how do I prepend one div so it moves from where it is to the first child of page wrapper? Commented Mar 8, 2014 at 0:14
  • 1
    @user3117555 - It doesn't work because prepend accept a node or an jQuery object instead of a String: jsfiddle.net/DerekL/eHq2a Commented Mar 8, 2014 at 0:16

3 Answers 3

3

You could use this with the window.resize() event if needed (you'd use an else statement to set it back to default as well)

$(document).ready(function(){
    $(window).resize(function(){    
     if ($(window).width() < 980) {
        $('#three').insertBefore('#one');
        $('#four').insertBefore('#two');
     } else {
      // Set back to default, or whatever you like.
     }
    });
});

jsFiddle here.

Sign up to request clarification or add additional context in comments.

1 Comment

This will work, though prependTo is probably a more logical method to use. api.jquery.com/prependTo
1

prepend does not accept a String selector. From the doc:

.prepend( content [,content] )
────────────────────────────────────────────────────────────────
content
Type: htmlString or Element or Array or jQuery

DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements.

You have to pass a jQuery object instead:

http://jsfiddle.net/DerekL/eHq2a/

$('#pageWrapper').prepend($('#three'));
$('#pageWrapper').prepend($('#four'));

//or just

$('#pageWrapper').prepend($('#four'), $('#three'));

However, interestingly .prependTo does accept a String selector:

$("#three").prependTo("#pageWrapper");

Comments

-1

Please use some responsive design then. In your case, use @media queries in CSS. Way better than doing it in script.

@media screen and (max-width:980px) {
/* your style */
}

If you still prefer to use script, then you can subscribe to the resize event handler like

$( window ).resize(function() {
  if($(window).width()<requiredMinimum)
  {
    //dowhatever
  }
  else
  {
    //revertback
  }
});

1 Comment

Good advice but ... how does this answer the question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.