My Blog: JQuery Page Inserts

07 January 2017

I wanted to alert users that some tables in my website were responsive and scrollable, but I didn't want to add additional text to my pages. I also wanted the notices to be appended automatically and in the same language as the website.

A table styled with Bootstrap looks fantastic, and when wrapped with the <div class="table-responsive"> tags, will scroll left / right on mobile devices with small screens. There's just one problem, it's not immediately obvious that the table is scrollable on the small screen. What I need is some way to tell website visitors that they can scroll the table.

Now, I could just manually add the message above tables in the CMS's Visual Editor like so:

This table is scrollable:

Key: Value:
A Aardvark
B Bumblebee

But if I have multiple editors working on my website, some might forget to add the message. There's also a requirement that the message only needs to appear on small screen devices, and that would require adding a class so that it could be hidden on large screens.

I need to find a way to automatically insert the message above all scrollable tables, without having to train or involve error-prone or forgetful editors.

Automatic Addition

So, how do you insert a message above scrollable tables? With a JavaScript JQuery function:

$(document).ready(function () {
    // Insert scrollable notice before each responsive table:
    $('div.table-responsive').each(function () {
        $('<p class="scrollable-table"><span class="label label-default">Scrollable table « »</span></p>').insertBefore(this);
    });
});

How it looks:

Key: Value:
A Aardvark
B Bumblebee

Different Languages

The next problem to solve is what to do about websites with multiple languages. Using the TextStrings function (previously discussed in my blog entry "Going International"), we have some hidden <div> tags on the page containing localised text strings. We can insert these into our function using $('div#table-responsive').data('store'), like so:

$(document).ready(function () {
    // Insert scrollable notice before each responsive table:
    $('div.table-responsive').each(function () {
        $('<p class="scrollable-table"><span class="label label-default">' + $('div#table-responsive').data('store') + '</span></p>').insertBefore(this);
    });
});

Small Screens Only

To make this message only appear on small screen devices, I can use CSS media rules to hide it on larger screens:

@media (min-width: 768px) {
    p.scrollable-table {
        display: none;
    }
}

comments powered by Disqus