blazerix blazerix - 1 year ago 63
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:

What I have done so far:

$(function () {
$("body").on('click', ".repeat", function (e) {
var $self = $(this);
var $parent = $self.parent();
} else {

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:

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

Answer Source

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.

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.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download