Column Visibility: What is the best way to organize columns?

Here is the code I currently have that is working: http://jsfiddle.net/tarabyte/s8Qds/3/

Javascript:

$(function() {    
(function generateStyleSheet(len){
    var styles = [], i = 0;

    for(; i < len; i++) {
        styles.push('.hide-' + i + ' .column-' + i + ' {display: none;}') ;
    }

    $('<style>' + styles.join('\n') + '</style>').appendTo(document.body);
}(100))

function Toggler(idx, text, table, togglers) {
    this.idx = idx;
    this.text = $.trim(text);
    this.table = table;
    this.togglers = togglers;
    this.init();
}

Toggler.prototype.init = function() {
    this.element = $('<span class="toggler" >' + this.text + '</span>').appendTo(this.togglers).data('toggler', this);
};

Toggler.prototype.toggle = function() {
    this.element.toggleClass('pressed');
    this.table.toggleClass('hide-'+this.idx);
};

function Togglers(el, table, hidden) {
    this.el = el.jQuery ? el : $(el);
    this.table = table.jQuery ? table : $(table);
    this.togglers = {};
    this.hidden = hidden||[];
    this.init();
}

Togglers.prototype.init = function() {
    var columns = 0, me = this;
    this.el.on('click', '.toggler', function(e){
        $(e.target).data('toggler').toggle();
    });

    this.table.find('th').each(function(idx, header){
        header = $(header);
        me.add(idx, header.text());
        header.addClass('column-' + idx);
        columns++;
    }).end()
        .find('td').each(function(idx, td) {
            $(td).addClass('column-' + (idx%columns));
        });

    $.each(this.hidden, function(_, name) {
        me.toggle(name);    
    });
};

Togglers.prototype.toggle = function(name) {
    var toggler = this.togglers[name];
    if(toggler) {
        toggler.toggle()
    }
    else {
        console.warn('Unable to find column with name: ' + name);
    }
};

Togglers.prototype.add = function(idx, name) {
    var toggler = new Toggler(idx, name, this.table, this.el);
    this.togglers[toggler.text] = toggler;
};

var togglers = new Togglers('#togglers', $('#table'), ['Color']);


togglers.toggle('Number');


})

CSS

.toggler {
    display: inline-block;
    padding: 5px 10px;
    margin: 2px;
    border: 1px solid black;
    border-radius: 2px;
    cursor: pointer;
}

.toggler.pressed {
    background-color: #BBB;
}

HTML

<div id="togglers"></div>
<table id="table">
    <tr>
        <th class="Title">ID</th>
        <th class="Title">Color</th>
        <th class="Title">Number</th>
    </tr>
    <tr>
        <td>1</td>
        <td>#990000</td>
        <td>C001</td>
    </tr>
    <tr>
        <td>2</td>
        <td>#009900</td>
        <td>C002</td>
    </tr>
    <tr>
        <td>3</td>
        <td>#FFFFFF</td>
        <td>C003</td>
    </tr>
    <tr>
        <td>4</td>
        <td>#000000</td>
        <td>C004</td>
    </tr>
</table>

I'm looking to group "Color" and "Number" so that when you click on "more info", it shows both. The order of the columns is unknown beforehand.

I attempted a solution here: http://jsfiddle.net/Ap9sQ/6/ However, I'm facing issues styling "more info" as grey by default and changing its color upon clicking.

Answer №1

I have a solution that I believe works well, but could it be considered good code?

Please disregard the variable names for now; I plan to update them with more appropriate ones.

http://jsfiddle.net/n4zzf/4/

Focus on the JavaScript portion (the rest is less crucial)

$(function() {    
(function generateStyleSheet(len){
    var styles = [], i = 0;

    for(; i < len; i++) {
        styles.push('.hide-' + i + ' .column-' + i + ' {display: none;}') ;
    }

    $('<style>' + styles.join('\n') + '</style>').appendTo(document.body);
}(100))

function Toggler(idx, text, table, togglers) {
    this.idx = idx;
    this.text = $.trim(text);
    this.table = table;
    this.togglers = togglers;
    this.init();
}
var navigation = 1;
var nav;
var DatesGroupNavigation = [];
var DatesGroupNavigation2 = [];
Toggler.prototype.init = function() {
    this.element = $('<span class="toggler navigation'+navigation+'" >' + this.text + '</span>').appendTo(this.togglers).data('toggler', this);
            switch (0){
             case this.text.indexOf("Title01"):
             case this.text.indexOf("Title02"):
             case this.text.indexOf("Title03"):
             case this.text.indexOf("Title04"):
                        DatesGroupNavigation.push(navigation);
                        break;
             case this.text.indexOf("Title1"):
             case this.text.indexOf("Title2"):
             case this.text.indexOf("Title3"):
             case this.text.indexOf("Title4"):
                        DatesGroupNavigation2.push(navigation);
                        break;
            }
            navigation++;
};

Toggler.prototype.toggle = function() {
    this.element.toggleClass('pressed');
    this.table.toggleClass('hide-'+this.idx);
};

function Togglers(el, table, hidden) {
    this.el = el.jQuery ? el : $(el);
    this.table = table.jQuery ? table : $(table);
    this.togglers = {};
    this.hidden = hidden||[];
    this.init();
}

var DatesGroupColumns = [];
var DatesGroupColumns2 = [];
var title;
Togglers.prototype.init = function() {
    var columns = 0, me = this;
    this.el.on('click', '.toggler', function(e){
        $(e.target).data('toggler').toggle();
    });


    this.table.find('th').each(function(idx, header){
        if(columns>0){ 
            header = $(header);
            me.add(idx, header.text());
            header.addClass('column-' + idx);
            title = header.text();
            switch (0){
             case title.indexOf("Title01"):
             case title.indexOf("Title02"):
             case title.indexOf("Title03"):
             case title.indexOf("Title04"):
                        console.warn(idx);
                        DatesGroupColumns.push(idx);
                        break;
             case title.indexOf("Title1"):
             case title.indexOf("Title2"):
             case title.indexOf("Title3"):
             case title.indexOf("Title4"):
                        console.warn(idx);
                        DatesGroupColumns2.push(idx);
                        break;
            }
        }
        columns++;
    }).end()
        .find('td').each(function(idx, td) {
            $(td).addClass('column-' + (idx%columns));
        });

    $.each(this.hidden, function(_, name) {
        me.toggle(name);    
    });
};

Togglers.prototype.toggle = function(name) {
    var toggler = this.togglers[name];
    if(toggler) {
        toggler.toggle()
    }
    else {
        console.warn('Unable to find column with name: ' + name);
    }
};

Togglers.prototype.add = function(idx, name) {
    var toggler = new Toggler(idx, name, this.table, this.el);
    this.togglers[toggler.text] = toggler;
};

var togglers = new Togglers('#togglers', $('#table'), ['Color']);
/*togglers.toggle('Client');*/
var Loop;
DatesGroupNavigationLength = DatesGroupNavigation.length;
for ( Loop = 0; Loop < DatesGroupNavigationLength; Loop++) {
    console.warn(DatesGroupNavigation[Loop]);
    $('.navigation'+DatesGroupNavigation[Loop]).addClass('HideColumn');
}
console.warn(DatesGroupColumns);
Loop = 0;
DatesGroupColumnsLength = DatesGroupColumns.length;
$('<span class="togglerExtra navigation'+navigation+'" >All title with 0</span>').appendTo($("#togglers")).click(function () {
                for ( Loop = 0; Loop < DatesGroupColumnsLength; Loop++) {
                    console.warn(Loop + " - test: " + DatesGroupColumns[Loop]);
                    $('.navigation'+ DatesGroupColumns[Loop]).data('toggler').toggle();
                }
                $('.navigation'+navigation).toggleClass("pressed");
            });
Loop = 0;
var navigation2 = navigation+1;
DatesGroupNavigationLength2 = DatesGroupNavigation2.length;
for ( Loop = 0; Loop < DatesGroupNavigationLength2; Loop++) {
    console.warn(DatesGroupNavigation2[Loop]);
    $('.navigation'+DatesGroupNavigation2[Loop]).addClass('HideColumn');
}
console.warn(DatesGroupColumns2);
Loop = 0;
DatesGroupColumnsLength2 = DatesGroupColumns2.length;
$('<span class="togglerExtra navigation'+navigation2+'" >All title without 0</span>').appendTo($("#togglers")).click(function () {
                for ( Loop = 0; Loop < DatesGroupColumnsLength2; Loop++) {
                    console.warn(Loop + " - test: " + DatesGroupColumns2[Loop]);
                    $('.navigation'+ DatesGroupColumns2[Loop]).data('toggler').toggle();
                }
                $('.navigation'+navigation2).toggleClass("pressed");
            });
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent Symfony2 Twig from rendering HTML content

Is there a way to disable the rendering of HTML responses in Twig? I am currently working on a RESTful API and my goal is to completely prevent HTML rendering. For instance, if I access /foo/bar without an oAuth Access Token, Symfony2 should reply with a ...

Guide to dynamically refreshing a section of the webpage while fetching data from the database

I'm currently developing a website using PHP & MySQL where some queries return multiple records. Each record has its own dedicated page, allowing users to navigate between them using arrows. So far, everything is working smoothly. However, I've ...

Differences Between Javascript Objects and JScript Dictionaries

When it comes to Javascript Objects and JScript Dictionaries, both are considered associative arrays. obj = new Object ; dic = new ActiveXObject("Scripting.Dictionary") ; My main inquiry is whether there are any differences between them in efficiency, wh ...

Incorporating ASP.NET server-side functionality with HTML5 for dynamic client-side 2D rendering

Currently working on a project that is about to begin, seeking advice and suggestions for available options. The main objective is allowing users to draw shapes like polygons while the server performs calculations based on various properties of these shap ...

The dropdown login form is malfunctioning on my Wordpress website

After reading various tutorials and guides online, I managed to set up a login screen. You can view the code in my jsfiddle: Jsfiddle. Unfortunately, I am facing issues with making the code function correctly. Being new to Jquery, I might have made a begin ...

How to display the total of specific values on the screen using React

Looking to create an app that displays 9 boxes, each with 4 select options: close successful, close unsuccessful, callback, and open. The goal is to count the number of closed successful and unsuccessful boxes and display the total count at the top of the ...

Guide to building a basic Table View for iOS with the help of HTML, Twitter Bootstrap, jQuery Mobile and more

I have experience with Objective-C, but I am still learning HTML/jQuery/JS. My goal is to create a Table view using these languages. Can anyone provide assistance by guiding me on how to achieve this? I was able to create a static Table view using the co ...

Unveiling the mystery of extracting information from a string post serialization

When working with a form, I am using this jQuery code to fetch all the field values: var adtitletoshow = $("#form_data").serialize(); After alerting adtitletoshow, it displays something like this - &fomdata1=textone&fomdata2=texttwo&fomdat ...

Ways to reach a variable beyond a subfunction in javascript

Below is a function I have created that utilizes a GLTF loader to import a model into the scene from another class: LoadModel(path){ this.gltfLoader.load( path, (gltf) => { this.scene.add(g ...

My goal is to dynamically assign a class to an iframe element by identifying a specific class contained within the html of the iframe

I need assistance with adding a class to an iframe only if the body tag has a specific class name. Here is my attempt at writing some code: <iframe class='iframeContent' src='' width='100%' height='' frameborder= ...

Learn how to insert a <TableRow> in a for loop using Object.keys

<TableBody> {(() => { var result = []; let key = Object.keys(genericResultList)[1]; var list = genericResultList[key]; for (var i = 0; i < list.length; i++) { ***\<!-- Add in the \<T ...

Adjust text alignment based on the mobile device screen size using Bootstrap 4

On smaller devices, the layout of my horizontal label and text field is not as I expected. It appears like the image below: https://i.sstatic.net/9I8Os.png I am trying to make the First Name label left-aligned on small devices. Here is the code I have be ...

Tips for executing a function only once within the animation loop in Three.js

Is there a way to call a function only once when a certain condition is met in Three.js? I am currently sampling the frames per second (FPS) to send it to an external service. The FPS is sampled and averaged over time, and the average value is sent after 1 ...

Leveraging the combination of <Form>, jQuery, Sequelize, and SQL for authentication and navigation tasks

My objective is to extract the values from the IDs #username-l and #pwd-l in an HTML form upon the user clicking the submit button. I aim to compare these values with those stored in a SQL database, and if they match exactly, redirect the user to a specifi ...

Display the current position of the caret in a field that cannot be edited

Can a virtual caret be displayed between two letter boundaries in HTML/CSS/JavaScript, for example in a regular div without using contenteditable=true? Imagine having the following: <div>Hello world</div> If I were to click between the "w" a ...

Performing a AJAX POST call to the latest Google Analytics V4 API

Recently, the Google Analytics v4 API was updated and now requires POST requests instead of GET requests. Unfortunately, there are not many examples available yet... I managed to obtain the accessToken, but when I attempt the following POST request, I alw ...

Angular method for monitoring element resizing detection

I'm having trouble with resizing using the UI-Calendar directive for Full Calendar. The div containing the calendar can change size based on an event, which modifies the div's class and therefore its size. However, when this occurs, the calendar ...

Struggling to implement CSS for second div onto selected item in the first div

As a beginner in Angular, I am seeking some guidance and examples. In my code, there are two divs. One is created using ng-repeat with an ng-click function to detect the clicked item. The other div below has CSS properties like style="width:100px; float ...

Looking for a simple method to convert JSON object properties into an array?

Is there a simple method for extracting only the values of the properties within the results object in the given JSON data? let jsonData = {"success":true, "msg":["Clutch successfully updated."], "results":{"count_id":2, ...

What is the reason behind this Uncaught TypeError that is happening?

After converting my questionnaire to a PHP file and adding a validation script, I encountered an error: Uncaught TypeError: Cannot set property 'onClick' of null The error is pointing me to line 163 in my JavaScript file, where the function f ...