blazerix blazerix - 2 months ago 15
jQuery Question

How to dynamically create two rows of squares in html/css/javascript

I'm trying to create 2 rows of 12 rectangles (considered to be one object).

I also want to add a plus button, so that when the user clicks on either end, a new set of rectangles appear above or below the original ones. (depending on which plus button they click on). I think I've got both plus buttons working.

So I am trying to achieve the following:

http://i.stack.imgur.com/P26sC.png

What I have done so far:

https://jsfiddle.net/zp5hnwmx/

$(function () {
$("body").on('click', ".repeat", function (e) {
e.preventDefault();
var $self = $(this);
var $parent = $self.parent();
if($self.hasClass("add-bottom")){
$parent.after($parent.clone());
} else {
$parent.before($parent.clone());
}
});
});


I am currently facing a bunch of issues:

When I run my code locally, the rectangles are not aligned properly and they wrap around to the next line (I want 2 rows of 12). This is what I see:

http://s16.postimg.org/ro0uzbrdx/Capture.png

After creating the rectangles, how can I access them individually?

Answer

Try adding white-space: nowrap; to whichever div is holding your square elements. Of course, this will create some overflow if the page is small, which will need to be handled by a parent element with overflow: auto; or some such statement.

Edit:
As for:

After creating the rectangles, how can I access them individually?

Whether or not attaching event listeners to each square is inefficient will depend on the performance requirements of your system. And the debates continue as to which is the most efficient structure. Now, this is purely subjective (as I only have a limited view of your project) and I do recommend you do further research... but I'd say that attaching one event listener to the most immediate parent container that wraps all your squares would be the best idea.

Since you can have an unknown amount of squares (potentially hundreds or thousands), you don't want to attach event listeners to each square. That's a huge memory sink of duplicate code. Instead, doing event listener delegation would be far better for memory efficiency. There will be a tiny bit more time waste but it should be O(1) and therefore negligible.

In summary, applying one event listener to a deep parent element (for example <div class="container">) would likely be the most efficient method for you.

Resources:
https://www.kirupa.com/html5/handling_events_for_many_elements.htm http://davewasmer.com/javascript-event-delegation/