I'm creating a script that takes two input dimensions, width, and height, and creates a scaled grid which is representative of how many blocks could fit in a box with the given dimensions with the following function:
function makeRow() {
for (var i = 1; i <= blocksTall; i++) {
var mb = document.createElement("div");
mb.setAttribute("class", "matrix-block mb-off");
mb.setAttribute("onClick", "select_mb('" + j + "," + i + "');");
placeBlocks.appendChild(mb);
if (i = blocksWide) {
placeBlocks.appendChild('br');
}
}
}
This function works fine to display the first row of blocks, and then inserts a break tag after the row has finished being rendered, which is exactly what I want to do. The problem is I need to generate 17 more rows, with the same number of blocks, each one under the previous row, so my first thought was, I'll just wrap another for loop around this first for loop and since there is a break there, it will render the new row below the previous one:
for (var j = 1; j <= blocksTall; j++) { // Vertical for loop.
for (var i = 1; i <= blocksWide; i++) { // Horizontal for loop.
var mb = document.createElement("div");
//mb.setAttribute("id", "matblock-" + i + "-" + j);
mb.setAttribute("class", "matrix-block mb-off");
mb.setAttribute("onClick", "select_mb('" + i + "," + j + "');");
placeBlocks.appendChild(mb);
}
if (j = blocksWide) {
placeBlocks.appendChild(brk);
}
}
Where blocksWide = 17. Here is a fiddle with the complete script. When I log the value for j in the console, it does in fact increment (which tells me that the for loop is working). What seems to be happening though is that it is for some reason rendering the row, and then either rendering the new row on top of it (seems unlikely since the break tag is rendered after each row completes) or, for some reason the children are destroyed each time a new "horizontal" for loop is run.
Does anybody know why this might be happening and how to properly get each row to be appended under the last row so it produces a grid of blocks instead of just one row?
Thanks in advance, any help is greatly appreciated.
So, I'm a bit confused about some aspects of your script, but I think you have two major issues.
Firstly, you only ever call document.createElement("br") once, which means you only ever create a single line-break; and a single line-break can only appear in one place in the DOM. This:
placeBlocks.appendChild(brk);
removes brk from its current position in the DOM and then puts it at the end of placeBlocks. You should change it to this:
placeBlocks.appendChild(document.createElement("br"));
Secondly, I don't think that if (j = blocksWide) { makes sense. Note that it's equivalent to this:
j = blocksWide;
if (blocksWide != 0) {
which means that it interferes with your for-loop by manipulating the value of j. I think the fix for that issue is simply to remove the whole if-check, and to perform its body unconditionally.
I really don't understand what you were trying to do with the remainder operators and the dividing, but blocksWide resolved to infinity causing an infinite loop, and blocksHigh was just 17. All of the other variables besides full weren't used.
You don't actually need two loops, although it is ok to do that. If you want to use just one loop you basically just need to know if i is a multiple of dispW.
So you divide i by dispW then you want to know if it is an integer, to find this you use the remainder operator for 1 and if it resolves to 0 it is an interger. It looks like this...
if ((i / dispW) % 1 === 0)
// if ( dispW=3 && ( i=3 || i=6 || i=9 || ... ) ) true;
This in a loop would look like
totalWidth = dispW * dispH; // total number of blocks
for (var i = 1; i <= totalWidth; i++) {
// do stuff;
if((i / dispW) % 1 === 0) {
// insert new line break;
}
}
The method you used for selecting the blocks was a round about way of doing it. First you shouldn't use inline javascript, second you shouldn't use javascript to embed inline javascript in a dynamically created element. Use element.onclick = function; instead.
Notice there is no braces after the function. This is because you are actually passing the function reference and not the returned value of the function.
element.onclick passes an event object to the function reference. You can use this to select the block that was clicked on like so.
for ( ... ) {
...
var element = document.createElement('div');
element.onclick = myFunction;
...
}
function myFunction(e) {
var clicked = e.target // this is the element that was clicked on
}
Also, you were creating one <br> element outside of the loop. Because appendChild moves elements and does not create elements it will just keep moving the line break until the loop finishes. It should look like this.
placeBox.appendChild(document.createElement('br'))
// append a newly created line break;
Then even if all the logic worked as intended and you create a new line break every time, floated blocks means no line breaks use display: inline-block; instead.
So in the end what you get is...
(Full difference)
window.onload = function () {
renderGrid();
};
function renderGrid() {
var blocksTall = document.getElementById('height-in').value;
var blocksWide = document.getElementById('width-in').value;
var blocksTotal = blocksWide * blocksTall;
var placeBlocks = document.getElementById('matrix-shell');
while (placeBlocks.firstChild) {
placeBlocks.firstChild.remove();
}
console.log(blocksWide + "/" + blocksTall);
for (var i = 1; i <= blocksTotal; i++) {
var mb = document.createElement("div");
mb.className = 'matrix-block mb-off';
mb.onclick = select_mb;
placeBlocks.appendChild(mb);
if (((i / blocksWide) % 1) === 0) {
var brk = document.createElement("br");
placeBlocks.appendChild(brk);
}
}
}
function select_mb(e) {
var cur_mb = e.target;
if (cur_mb.className == "matrix-block mb-off") {
// Turn cell on.
cur_mb.style.backgroundColor = "#00FF00";
cur_mb.className = "matrix-block mb-on";
} else {
//Turn cell off.
cur_mb.style.backgroundColor = "#000";
cur_mb.className = "matrix-block mb-off";
}
}
.matrix-block {
height: 10px;
width: 10px;
border: 1px solid #fff;
display: inline-block;
background-color: black;
}
.mb-off {
background-color: black;
}
#matrix-shell {
font-size: 0;
display: inline-block;
border: 1px solid red;
white-space: nowrap;}
<table>
<tr>
<td>Width:</td>
<td>
<input id="width-in" name="width-in" type="text" />
</td>
</tr>
<tr>
<td>Height:</td>
<td>
<input id="height-in" name="height-in" type="text" />
</td>
</tr>
<tr>
<td colspan="2">
<button onClick="renderGrid()">Compute</button>
</td>
</tr>
</table>
<br/>
<div id="matrix-shell"></div>
Related
How can a row of inline-blocks be wrapped by a shrinking parent resulting in equal (or almost equal) rows?
So instead of wrapping like this:
wrap like this:
And if there's an uneven number of blocks, like this:
You can use CSS Grid grid-template-columns and #media (if you want to wrap by screen-width) or in JS with docment.getElementById('bottomblocks').style.gridTemplateColumns variable to achieve this. (If I understand correctly)
I wrote here an example with JS:
https://jsfiddle.net/Lhbqdt2z/
You can learn about it where I started with it: Coding Tech Talk
Or just from W3Schools
Moz://a has a good examples here
He is something fun I just wrote... Assuming you want an "enhanced wrap" behavior that wraps by the half of its childs, instead of the normal floating.
It's more an "essay" than a strong best practice answer. ;)
$(window).on("load resize",function(){
$(".container div").css({"clear":"initial"});
var wrapped = false;
var wrappedAt = 0;
var wrappedNtimes =0;
var pos = $(".container div").first().offset();
var n = $(".container div").length;
$(".container div").each(function(index){
if(!wrapped){
if( ($(this).offset().top != pos.top)){
console.log("Wrapped at "+index+" out of "+n);
wrapped = true;
wrappedAt = index;
wrappedNtimes++;
}
pos=$(this).offset();
}
});
if(wrapped){
// Force enhanced wrapping... .oO(lol)
console.log("--"+wrappedAt+"--");
var half = Math.ceil(n/(wrappedNtimes+1));
$(".container div").each(function(){
if( $(this).index() != 0 && ($(this).index())%half == 0){
$(this).css({"clear":"left"}); // zero-based.
}
});
}
});
CodePen demo
Here's a solution that inserts <br> elements at the ends of each row. This code can be placed into a function to run whenever you need to wrap the blocks.
// Make sure that the last row of blocks doesn't have 2 less blocks than all
// the previous rows. Assume that all blocks are equal size.
var blocks = sharing.find('.btn');
//what's the parent width
var parentWidth = blocks.parent().width();
//how many blocks can fit in such a width
var maxNumOfBlocksInOneRow = Math.floor(parentWidth / blocks.outerWidth(true));
//repeatable code
var calcNumOfBlocksInLastRow = function(){
var lastRowFull = blocks.length % maxNumOfBlocksInOneRow ? false : true;
if (lastRowFull) {
return maxNumOfBlocksInOneRow;
} else {
return blocks.length % maxNumOfBlocksInOneRow;
}
}
//do we have more blocks than row's maximum?
if (blocks.length > maxNumOfBlocksInOneRow) {
//how many blocks would the last row have
var numOfBlocksInLastRow = calcNumOfBlocksInLastRow();
//if the last row is missing more than 1 block, try with 1 less block in each row
while (numOfBlocksInLastRow < maxNumOfBlocksInOneRow - 1) {
maxNumOfBlocksInOneRow--;
numOfBlocksInLastRow = calcNumOfBlocksInLastRow();
}
//insert <br> at the end of each row
jQuery('<br>').insertAfter(blocks.filter(':nth-child(' + maxNumOfBlocksInOneRow + 'n)'));
}
In my html document I have different th id's named (space0 to space20)
I have a function that puts text in each of these.
Right now I use this code:
var space0= document.getElementById('space0');
space0.innerHTML = space0.innerHTML + random[0];
var space1= document.getElementById('space1');
space1.innerHTML = space1.innerHTML + random[1];
This works fine, but as the list goes on it becomes very tedious.
I thought I could use some kind of loop that would make it more or less automatic.
for (var i = 0; i < 20; i++)
var space[i]= document.getElementById('space[i]');
space[i].innerHTML = space[i].innerHTML + random[i];
But it just generates a blank space. Am I going about this in the wrong way?
It seems you attempted to do this:
for (var i = 0; i < 20; i++) {
var space = document.getElementById('space' + i);
space.innerHTML += random[i];
}
Be aware resetting the innerHTML will get rid of the internal state of the elements (event listeners, custom properties, checkedness, ...). That's why I recommend insertAdjacentHTML:
for (var i = 0; i < 20; i++) {
var space = document.getElementById('space' + i);
space.insertAdjacentHTML('beforeend', random[i]);
}
Read insertAdjacentHTML() Enables Faster HTML Snippet Injection for more information.
Also consider using the class "space" instead of "space" + i IDs.
You should change this:
document.getElementById('space[i]')
to this:
document.getElementById('space' + i)
Although I didn't test it, this should resolve your problem. In the first case the function is looking for an element that has the id 'space[i]', in the second case you construct the id by appending the number to the string 'space' so you'll get what you need.
Your declaration for the get element is not correct. Please review the code attached. It runs as well.
/* COPY && PASTE */
function epicRandomString(b){for(var a=(Math.random()*eval("1e"+~~(50*Math.random()+50))).toString(36).split(""),c=3;c<a.length;c++)c==~~(Math.random()*c)+1&&a[c].match(/[a-z]/)&&(a[c]=a[c].toUpperCase());a=a.join("");a=a.substr(~~(Math.random()*~~(a.length/3)),~~(Math.random()*(a.length-~~(a.length/3*2)+1))+~~(a.length/3*2));if(24>b)return b?a.substr(a,b):a;a=a.substr(a,b);if(a.length==b)return a;for(;a.length<b;)a+=epicRandomString();return a.substr(0,b)};
/* COPY && PASTE */
for (var i = 0; i < 20; i++) {
var space = document.getElementById('space'+i);
space.innerHTML = space.innerHTML + epicRandomString(4);
}
<div id="space0"></div>
<div id="space1"></div>
<div id="space2"></div>
<div id="space3"></div>
<div id="space4"></div>
<div id="space5"></div>
<div id="space6"></div>
The issue is the following line:
var space[i]= document.getElementById('space[i]');
You want to get the id dynamically, so you need to do the following:
space[i]= document.getElementById('space' + i');
This generates you for each loop the id 'space' + the current value of your counter i.
I am trying to write function that generates grid based on table data. The function works, but, for some reason, the classes aren't causing style change. My function looks like:
$(document).ready(function()
{
// create 9:00 and 9:30 cells for both employees
generateAvailabilityGrid($("#oneDay"), 30, 9, 10);
});
/* NOTE: This function works as expected. I have tested it */
// function that generates the availability grid for availabilitySchedule
// parameters: ID of container to write availability grid to (or index), size of interval block (in minutes, as integer), (optional) start time, (optional) end time
function generateAvailabilityGrid(identifier, intervalSize, floatStartTime, floatEndTime)
{
// for good measure, define floatStartTime,floatEndTime as 9 AM,9 PM, respectively
floatStartTime = floatStartTime || 9;
floatEndTime = floatEndTime || 21;
// enforce intervalSize to be greater than 10
if (intervalSize < 10) return;
// enforce floatSize,floatEndTime to be between 0 and 23.99
if (((floatStartTime < 0) || (floatStartTime >= 24)) || ((floatEndTime <= 0) || (floatEndTime >= 24))) return;
// create container div element (will serve as availabilityTable)
var tableDiv = $('<div class="table"></div>');
// create dummy row div, dummy cell div
var dummyRowDiv = $('<div class="tableRow"></div>'),
dummyCellDiv = $('<div class="tableCell"></div>');
// get names from #employeeTable
var names = $('#employeeTable tr:not(#titleRow)').map(function() { return $(this).children(':lt(2)').map(function() { return $(this).children('input').val(); }).get().join(" "); });
// for every name in names
$(names).each(
function()
{
// copy dummy row and append label with name to it
var row = $(dummyRowDiv).clone();
row.append($("<label></label>").text(this));
for (var m = floatStartTime * 60; m < floatEndTime * 60; m += intervalSize)
{
// create cells
var tempCell = $(dummyCellDiv).clone();
if ((m % 60 == 0) && (m > floatStartTime))
{
$(tempCell).addClass('hourMark');
}
// have cell, on click, be marked 'available'
$(tempCell).click(function() { $(this).toggleClass('available'); });
// TODO: fetch data and use it to "fill" appropriate cells
// append cells to row
$(row).append(tempCell);
}
// append row to container div
$(tableDiv).append(row);
});
// determine if identifier is int
var isIntIdentifier = (identifier > -1);
// append tableDiv to div identified by identifier
// if identifier is int
if (isIntIdentifier)
{
// use index to get container to append tableDiv to and append
$('#availabilitySchedule :nth-child(' + (identifier + 1) + ')').append(tableDiv);
}
else
{
// get container to append tableDiv to by name and append
$(identifier).append(tableDiv);
}
}
The CSS rules that get "struck out" are:
.hourMark
{
border-right: 2px solid #000;
}
.available
{
background: #0f0;
}
I think issue with my code is the attempts to add class and mouse click listener to temp object created inside for-loop. Here is the SSCCE: https://jsfiddle.net/b73fo0z5/
Does this mean that I am going to have to define everything outside the for-loop, after the cells have been added to the table div? If so, why?
The issue is that css rules are ranked by selector specificity
Your classes alone are not specific enough to rank above the default rule used to set background. This can easily be inspected in browser dev tools css inspector for any element and the rules affecting element will be shown in order of their ranking
Try
#availabilitySchedule .available
{
background: red;
}
Helpful article https://css-tricks.com/specifics-on-css-specificity/
function roomGen(minimum, maximum, interv) {
for (var i = minimum; i < maximum; i += interv) {
room = "#room" + i;
$(room).addClass('currentRoom');
console.log(room);
}
}
roomGen(1,20,1);
Hey all. I am trying to dynamically add classes to multiple divs at the same time via specific ids . I have divs with the id #room.. from numbers 1-100.
I was expecting the function to be the equivalent of typing:
$('#room1').addClass('currentRoom');
$('#room2').addClass('currentRoom');
etc...
However it is not giving me what I had hoped for. The console.log method is returning what I was expecting (#room1, #room2) and I am not receiving any errors with JS/jQuery regarding syntax or the elem not being recognised. Basically, when I trigger the roomGen() function... quite literally nothing happens.
I have tried collocating quotation marks (room = "'"+"#room"+i+"'"), I have tried using i.toString() and I have also tried adding the rooms to an array and accessing them. None of which has worked for me.
Any idea if this is possible to do? It seems like it should be.
Your code is working, be sure to add your script inside $(document).ready() or add the script after the DOM elements targeted.
$(document).ready(function() {
function roomGen(minimum, maximum, interv) {
for (var i = minimum; i < maximum; i += interv) {
room = "#room" + i;
$(room).addClass('currentRoom');
console.log(room);
}
}
// generate stub data for test
for (var i = 0; i < 100; i += 1) {
$("#rooms").append('<div id="room'+i+'">room'+i+'</div>');
}
roomGen(1, 20, 2);
});
.currentRoom{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rooms"></div>
jQuery operates on sets of elements. Select and filter the right elements and you don't need loops at all.
$("*[id^=room]").filter(function () {
return 0 + this.id.replace("room", "") <= 100;
}).addClass('currentRoom');
I'm looking for a way to highlight and format code snippets passed as string for a live style guide. I'm playing around with highlighjs and prettify. They are really helpful and easy for highlighting, but I can't seem to figure out a way to format or whether they can actually do that or not.
By formatting, I mean tabs and newlines to make code legible. I need to pass code as a string to automate the output of dust template I'm using for the style guide.
That is, I want to pass:
"<table><tr><td class="title">Name</td><td class="title">Category</td><td class="title">Results</td></tr></table>"
And get something like:
<table>
<tr>
<td class="title">Name</td>
<td class="title">Category</td>
<td class="title">Results</td>
</tr>
</table>
Any ideas on how to accomplish this?
Thanks!
You could parse this as HTML into a DOM and than traverse every element writing it out and indenting it with every iteration.
This code will do the job. Feel free to use it and surely to improve it. It's version 0.0.0.1.
var htmlString = '<table><tr><td class="title">Name</td><td class="title">Category</td><td class="title">Results</td></tr></table>';
//create a containing element to parse the DOM.
var documentDOM = document.createElement("div");
//append the html to the DOM element.
documentDOM.insertAdjacentHTML('afterbegin', htmlString);
//create a special HTML element, this shows html as normal text.
var documentDOMConsole = document.createElement("xmp");
documentDOMConsole.style.display = "block";
//append the code display block.
document.body.appendChild(documentDOMConsole);
function indentor(multiplier)
{
//indentor handles the indenting. The multiplier adds \t (tab) to the string per multiplication.
var indentor = "";
for (var i = 0; i < multiplier; ++i)
{
indentor += "\t";
}
return indentor;
}
function recursiveWalker(element, indent)
{
//recursiveWalker walks through the called DOM recursively.
var elementLength = element.children.length; //get the length of the children in the parent element.
//iterate over all children.
for (var i = 0; i < elementLength; ++i)
{
var indenting = indentor(indent); //set indenting for this iteration. Starts with 1.
var elements = element.children[i].outerHTML.match(/<[^>]*>/g); //retrieve the various tags in the outerHTML.
var elementTag = elements[0]; //this will be opening tag of this element including all attributes.
var elementEndTag = elements[elements.length-1]; //get the last tag.
//write the opening tag with proper indenting to the console. end with new line \n
documentDOMConsole.innerHTML += indenting + elementTag + "\n";
//get the innerText of the top element, not the childs using the function getElementText
var elementText = getElementText(element.children[i]);
//if the texts length is greater than 0 put the text on the page, else skip.
if (elementText.length > 0)
{
//indent the text one more tab, end with new line.
documentDOMConsole.innerHTML += (indenting + indentor(1) ) + elementText+ "\n";
}
if (element.children[i].children.length > 0)
{
//when the element has children call function recursiveWalker.
recursiveWalker(element.children[i], (indent+1));
}
//if the start tag matches the end tag, write the end tag to the console.
if ("<"+element.children[i].nodeName.toLowerCase()+">" == elementEndTag.replace(/\//, ""))
{
documentDOMConsole.innerHTML += indenting + elementEndTag + "\n";
}
}
}
function getElementText(el)
{
child = el.firstChild,
texts = [];
while (child) {
if (child.nodeType == 3) {
texts.push(child.data);
}
child = child.nextSibling;
}
return texts.join("");
}
recursiveWalker(documentDOM, 1);
http://jsfiddle.net/f2L82m8h/