Control Where Element Should Be In The DOM - jQuery AppendAround

Control Where Element Should Be In The DOM - jQuery AppendAround
File Size: 7.08 KB
Views Total: 105
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A pattern for responsive markup.

Sometimes, complex responsive layouts are hindered by source order. This pattern allows you to control where an element should be in the DOM by setting one of its potential parent containers (paired in the source with matching data-set attributes) to display: block at a particular breakpoint.

You might find this useful when embedding ads that need to be early in the source on a small-screen device, but later in the source in a desktop scenario. Or perhaps you'd use it to serve mobile-first navigation at the end of the page, while ensuring it's up top at wider viewports. Either way, this pattern can alleviate the need for server-side reliance when negotiating source-order discrepancies across layouts.

How to use it:

1. Include the AppendAround plugin after jQuery.

<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/src/appendAround.js"></script>

2. Insert potential element containers throughout the DOM. Give each container a data-set attribute with a value that matches all other containers' values

<!-- potential container for appendAround -->
<div class="foo" data-set="foobarbaz"></div>

...

<!-- potential container for appendAround -->
<div class="bar" data-set="foobarbaz"></div>

...

<!-- initial container for appendAround -->
<div class="baz" data-set="foobarbaz">

...

3. Place your appendAround content in one of the potential containers.

<div class="baz" data-set="foobarbaz">
  <p class="sample">Sample appendAround Element</p>
</div>

4. Call the appendAround() on that element when the DOM is ready.

$( ".sample" ).appendAround();

5. Example CSS.

.sample {
  padding: 1em;
  background: tan;
}
  
.baz {
  display: block;
}
.foo,
.bar {
  display: none; 
}
  
@media (min-width: 30em){
  .bar {
    display: block;
  }
  .foo, .baz {
    display: none; 
  }
}
  
@media (min-width: 50em){
  div.foo {
    display: block;
  }
  div.bar, div.baz {
    display: none; 
  }
}

This awesome jQuery plugin is developed by filamentgroup. For more Advanced Usages, please check the demo page or visit the official website.