Is it possible to limit the maximum number of children a div can have?

css, drag-and-drop, javascript, jquery

Solution

You could check if the container has too many elements and save the parent element when dragging like this

function drag(ev) {
    itemParent = ev.target.parentElement;
    //console.log(itemParent);
    ev.dataTransfer.setData("Text", ev.target.id);
};

function drop(ev) {
    ev.preventDefault();
    if (ev.target.childNodes.length == 4) {
        var data = ev.dataTransfer.getData("text");
        console.log(itemParent);
        itemParent.appendChild(document.getElementById(data));
    } else {
        var data = ev.dataTransfer.getData("Text");
        ev.target.appendChild(document.getElementById(data));
    }
};

DEMO

with jQuery

function drop(ev) {
    ev.preventDefault();
    if ($('.commands').not(itemParent).children().length == 4) {
        var data = ev.dataTransfer.getData("text");
        console.log(itemParent);
        itemParent.appendChild(document.getElementById(data));
    } else {
        var data = ev.dataTransfer.getData("Text");
        $('.commands').not(itemParent).append($('#' + data));
        //ev.target.appendChild(document.getElementById(data));
    }
};

This code is better, so you can drop the elements on elements so you don't append to the boxes.

DEMO

Problem

So I want to limit the number of children a `div` can have. The idea is that you have a `selected commands div` where you can drag and drop whichever commands (essentially buttons) are available to you at any given time, from another `div` called `available commands`, but only up to a maximum of four at a time. Here's the fiddle: http://jsfiddle.net/v9Fg8/2/ How can I limit the number of maximum possible children this `div` can have, so that when it reaches 4, one of the children gets replaced on the `drop` event.

Original source