Insert date event into a table if page width is less than certain value

1

What I want to do is that when the width of the page is less than the value shown below it will enter data-tablesaw-mode="stack in the site shown below! I'm new to JavaScript but I need this for a project! Thanks to anyone who helps I am available to provide any information that is important.

What I want to insert

 data-tablesaw-mode="stack"

How I'm trying to do

<script>
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
var table = document.getElementsById('table-hide');

if width<39.9375em {
   table. += "data-tablesaw-mode="stack";
}
</script>

HTML where I want to insert

<table id="table-hide" class="tablesaw tablesaw-stack">
    
asked by anonymous 22.06.2018 / 11:50

2 answers

2

To work as desired, you should place the document to listen for the event resize , create a function:

function screen_width() {
    var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    if(width < 400) {
        // Adiciona o atributo
        tabela.setAttribute('data-tablesaw-mode', 'stack');
    } else {
        // Remove o atributo
        tabela.removeAttribute('data-tablesaw-mode');
    }
}

Then place the document to listen for the event:

// Escuta o evento
window.addEventListener('resize', screen_width);

Call the function to check when the page loads.

// Executa a primeira vez
screen_width();

Complete code:

var tabela = document.getElementById('table-hide');

function screen_width() {
    var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    if(width < 400) {
        // Adiciona o atributo
        tabela.setAttribute('data-tablesaw-mode', 'stack');
    } else {
        // Remove o atributo
        tabela.removeAttribute('data-tablesaw-mode');
    }
}

// Escuta o evento
window.addEventListener('resize', screen_width);

// Executa a primeira vez
screen_width();

References:

22.06.2018 / 12:45
1

Try to do so

var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; 

if(width < 39.9375){ //Valor em pixeis
   document.getElementById('table-hide').setAttribute("data-tablesaw-mode", "stack");
}
    
22.06.2018 / 11:58