Vincent Chua
Vincent Chua

Reputation: 1009

Swap html elements using Jquery?

I want to switch the html elements inside my html when my screen size get below 880px, however it doesn't work as I expected...

I have few posts inside my html generated from a php loop, for each post it looks like this:

<div class="post">
  <h1>Lorem ipsum</h1>
  <p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

  </p>
</div>

What I want to do is when my browser screen get to 880px and below, the h1 and p elements will swap with each other using jquery insertBefore.

Below is my code:

http://codepen.io/vincentccw/pen/GHnFD?editors=101

Upvotes: 0

Views: 788

Answers (2)

pmandell
pmandell

Reputation: 4328

$(document).ready(function () {

    $(window).resize(divSwap);

    function divSwap() {
        if ($(document).width() <= 880) {
            $('.post').each(function () {
                $el = $(this);
                $el.find('p').insertBefore( $el.find('h1') );
            });
        }
    }

    divSwap();

});

Upvotes: 3

deebs
deebs

Reputation: 1410

You could add another h1 tag below the p tag and hide the first one on mobile, and show the second on mobile. I hate to duplicate info, but that's a quick easy fix:

<div class="post">
<h1 class="MobileHide">Lorem ipsum</h1>
<p>

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

</p>
<h1 class="MobileOnly">Lorem ipsum</h1>
</div>

Then in your CSS the "MobileHide" class is display:inline or block above 880px, and display:none below. And the "MobileOnly" class is display:none above 880px, and display: block or inline below it.

Hope that helps!

Upvotes: 1

Related Questions