Generate table row break conditionally

I have a <table> with two cells that I want to display horizontally if device is computer or vertically if it's mobile. I borrowed a JS function to detect mobile from this answer https://stackoverflow.com/a/11381730/3298930 that works great.

My horizontal table looks like this (actually, it's more complicated, but I want to make it simple) :

<table>
  <tr>
    <td> <video>s </td>
    <td> description and capture data </td>
  </tr>
</table>

In order to make it vertical I only need to insert two tags :

<table>
  <tr>
    <td> <video>s </td>
  </tr> ◄────────────────────────────┐
  <tr>  ◄────────────────────────────┘
    <td> description and capture data </td>
  </tr>
</table>

My question is : how can I insert those two tags by calling a JS function? I wish I could do something like this :

<table>
  <tr>
    <td> <video>s </td>

<script>
if ( mobile() ) write "</tr>
                       <tr>";
</script>

    <td> description and capture data </td>
  </tr>
</table>

mobile() is the JS function that returns TRUE if device is mobile.

I found two answers about manipulating the DOM (https://stackoverflow.com/a/18333557/3298930 and https://stackoverflow.com/a/27525472/3298930) but I couldn't make it work, here it is :

<table>
  <tr>
    <td id="my_td"> <video>s </td>

<script>
if ( mobile() ) $("#my_td").append("</tr><tr>");
</script>

    <td> description and capture data </td>
  </tr>
</table>

Upvotes: 1

Views: 690

Answers (1)

Vinay
Vinay

Reputation: 7676

If you want to do only on initial load

function isMobile() {
    return true; // or false
}

$(function () {

    if (isMobile()) {
        $td = $('#tbl').find('#row1_item2').detach();
        $a = $('#row1').after(`<tr id="row2"></tr>`);

        $('#row2').append($td);
    }

    $('#row1_item2').css('display', 'table-row');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table id="tbl">
    <tr id="row1">
        <td id="row1_item1">a</td>
        <td id="row1_item2" style="display: none;">b</td>
    </tr>
</table>

Upvotes: 1

Related Questions