s.spirit
s.spirit

Reputation: 343

Deselect element, when click to another element

I have a simple interface, wich allow to User add elements dynamically and drag them around. But I need to add a feature, that show to User selected element. And when User will click to another element, all other elements must be deselected...

I create simple function, that bring a special CSS class to the element, that User select, but I dont understand, how to remove that class from all another dynamically added elements, when User select another one.

I found some solutions in jQuery, but I need to write it with pure JS.

How can I do it? It must be some kind of cycle function?

My template:

    <head>
        <title>Int Demo</title>
        <script src='js/jquery.js'></script>
        <script src='js/jquery-ui.min.js'></script>
        <script src='js/script.js'></script>
        <style type="text/css">
            .button {width: 100px; height: 20px; background: #A3A1A1; text-align: center; font-size: 12px; color: #ffffff; padding-top: 6px; cursor: pointer;}
            .wrapper {width: 800px; height: 300px; background: #D4D1D1; position: relative;}
            .textblock {cursor: pointer; position: absolute; left: 5%; top: 5%;}
            .selected {border: 1px solid red;}
        </style>
    </head>

    <body>
        <div class="button" id="button">Add Textbox</div>
        <div class="wrapper" id="wrapper"></div>
    </body>

</html>

My JS:

document.addEventListener("DOMContentLoaded", function() { init(); }, false);

function init() {

    button = document.getElementById('button');
    wrapper = document.getElementById('wrapper');

    button.addEventListener('click', btnClick, false);
    document.addEventListener('mousedown', selector, false);

    function selector(e) {
        var select = e.target;
        if (select.classList.contains('draggable')) {
            select.classList.add('selected');
        };
        console.log(select);
    };


    function btnClick() {
        wrapper.innerHTML += '<p class="draggable textblock">Text Here!</p>';
    };

}

Upvotes: 1

Views: 2935

Answers (1)

epascarello
epascarello

Reputation: 207527

Find the element[s] and remove them

if there is just one, than remove the class before you add the other one.

document.querySelector(".selected").classList.remove('selected');

Upvotes: 1

Related Questions