Search code examples
htmlcssselectclickclone

Click , Select and Clone to another field


I would like to create a scene which would help me to copy some items by click and select option.

Here is a JSFiddle, if you go ahead and have a look on the scene. you'll see 1 Red, 1 Blue and 1 Green boxes.

#container {
    width:500px;
    height:600px;
    display:block;
}
#red {
    display:inline-block;
    width:50px;
    height:50px;
    background-color:red;
}
#blue {
    display:inline-block;
    width:50px;
    height:50px;
    background-color:blue;
}
#green {
    width:350px;
    height:350px;
    background-color:green;
}

HTML:

<div id="container">
    <div id="red"></div>
    <div id="blue"></div>
    <div id="green"></div>
</div> 

My purpose is selecting one of the small boxes either blue or red by clicking "ONCE" and when I click anywhere inside the Green box I would like to clone inside. For instance, If I click to Red, it must be selected and when I click inside the Green box I must clone it as many times as I click inside the box.

Which way I should follow to do this and what kind of captions I should start searching for the method?

I found this following link but it wasn't very much helpful to get the idea; http://simonsarris.com/blog/140-canvas-moving-selectable-shapes

Thank you very much for your help from now.


Solution

  • I have figured a way to handle this case. Without Javascript you can't do handle it. Whereas here I have used jQuery and here is my logic:

    1) I have created a global variable isRedOrBlue to identify what element user have selected. Whenever I click the red or blue div, I will be changing it accordingly.

    var isRedOrBlue;
    $('#red').on('click', function () {
        isRedOrBlue = "red";
        // For identification, I'm adding border
        $(this).css({
            "border": "1px solid #ccc"
        });
        //Vice versa I'm removing for other
        $('#blue').css({
            "border": ""
        })
    });
    $('#blue').on('click', function () {
        isRedOrBlue = "blue";
        // For identification, I'm adding border
        $(this).css({
            "border": "1px solid #ccc"
        })
        //Vice versa I'm removing for other
        $('#red').css({
            "border": ""
        })
    });
    

    2) Now when I click the green div, based on isRedOrBlue variable I will be cloning it and appendTo it to the green div.

    $('#green').on('click', function () {
        if (isRedOrBlue) { // When none selected
            console.log(isRedOrBlue)
            $('#' + isRedOrBlue).clone().appendTo($(this));
        }
    });
    

    JSFiddle

    Hope you can understand my logic that I've used above.