Search code examples
javascriptwordpressamp-html

AMP: add <table> to a <div>


I use a jQuery script to append all the <table>s of a WordPress post to a <div> with the class .table_container.

This way, I can make every table scrollable on mobile devices on already posted articles.

jQuery:

for (var r = document.querySelectorAll("#post table"), m = 0; m < r.length; m++) {
    var i = r[m],
        d = document.createElement("div");
    i.parentElement.insertBefore(d, i), d.className = "table_container", d.appendChild(i)
}
e(".table_container").before("<small>Scroll to see more</small>");

CSS:

.post .table_container {
    max-width: 100%;
    overflow-x: auto;
}

How can I do the same on AMP, since it's not possible to use Javascript?

I am currently using AMP for WP


Solution

  • Since AMP does not allow arbitrary JS, one of the applied design principles is to solve issues like this at the right layer (e.g. server side, CSS). In your particular case, you can make the tables scrollable using only CSS as described here:

    table {
      margin: auto;
      border-collapse: collapse;
      overflow-x: auto;
      display: block;
      width: fit-content;
      max-width: 100%;
      box-shadow: 0 0 1px 1px rgba(0, 0, 0, .1);
    }
    

    or you can generate the markup in PHP as suggested in a prior answer. These approaches remove the need of JS code, making them suitable to AMP.