Search code examples
javascripthtmlcssreverse-engineeringcss-tables

Selected dimensions convert to div table


Can anyone help me reverse engineer this or this page? Where the user selects the dimensions via a grid system. Then the amount of selected boxes gets converted into div's, in the same dimensions.

Or does anyone recommend and a JavaScript, if so which one?


Solution

  • we have two issues here, one is selecting and one is generating. Generating is simple:

    Notice: This is done quick and dirty; innerHtml should not be used, Ping me if you'd like to see it more polished :) https://jsfiddle.net/ynfb3Lh2/9/

    <div id="selection">
    </div>
    <div id="target">
    </div>
    <pre id="text">
    </pre>
    
    <script>
      // Prepare our targets
      const selectionContainer = document.getElementById("selection");
      const targetContainer = document.getElementById("target");
      const textContainer = document.getElementById("text");
    
      // rows: How many rows to generate?
      // cols: How many cols to generate?
      // [_insertCallback]: should we insert callback? 
      // [_targetContainer]: where should we place created divs?
      // [_textContainer]: sWhere should we write our HTML as plain text? 
      function generateDiv(rows, columns, _insertCallback, _targetContainer, _textContainer) {
        // Create our wrapping elements
        const table = document.createElement("table");
        const tbody = document.createElement("tbody");
    
        for (let r = 0; r < rows; ++r) {
          // Each row is created here...
          const tr = document.createElement("tr");
    
          for (let c = 0; c < columns; ++c) {
            const td = document.createElement("td");
            td.text = "&nbsp;"
            // if callback is defined, and we have a target - allow us to generate new table on each click
            if (_insertCallback && _targetContainer) {
              td.onclick = () => generateDiv(r + 1, c + 1, false, _targetContainer, _textContainer)
            }
    
            tr.appendChild(td)
          }
    
    
          // ... and added here
          tbody.appendChild(tr)
        }
    
        table.appendChild(tbody)
    
        if (_targetContainer && !_insertCallback ) {
          _targetContainer.innerHTML = '';
          _targetContainer.appendChild(table);
        }
        if (_textContainer && !_insertCallback ) {
          _textContainer.innerHTML = table.outerHTML
          .replace(/td><\//gi, "td>&amp;nbsp;</")
          .replace(/</gi, "&lt;")
          .replace(/>/gi, ">\n");
        }
    
        return table;
      }
    
      selectionContainer.appendChild(generateDiv(10, 10, true, targetContainer, textContainer));
    
    </script>
    

    and similarily, making a selectable table is done via similar function that adds row and col information to each cell. Then, a mouseClick event on table will read the rows and cols and pass to the generation code.