Lab - Dom Walk

Find the flags

by Kaushik Ruparel

HTML

<div id="container">
     <h1>Find the flag elements.</h1>

    <p>There are three flags ("FLAG") in the content below. When a user clicks on a flag, move it into the #bucket element.</p>
    <div class="main">
        <ul>
            <li>One</li>
            <li>FLAG #1</li>
            <li>Three</li>
        </ul>
        <div id="articles">
            <article class="new">
                 <h3>Article 1</h3>

                <p>This is <a href="#">some</a> body content</p>
                <p>This is some body content <a class="flag" href="#">FLAG #2</a>

                </p>
            </article>
            <article class="new">
                 <h3>Article 2</h3>

                <p>This is some body content</p>
            </article>
            <article>
                 <h3>Article 3</h3>

                <p>This is some body content</p>
            </article>
            <div class="footer">
                <div>
                    <div>
                        <div></div>
                        <div>
                            <div>FLAG #3</div>
                            <div></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div id="bucket">
         <h2>Dropped Flags:</h2>

        <!-- Where are my flags? -->
    </div>
</div>

CSS

body {
    font-size:.7em;
}
#bucket {
    position:absolute;
    top:5px;
    right:5px;
    border:2px solid #ccc;
    border-radius:2px;
    border-top:0;
    background-color:#ececec;
    width:20%;
    font-size:8px;
}
#bucket::before {
    content:"Bucket";
}
#bucket a, #bucket div, #bucket li {
    display:block;
    color:red;
}

JavaScript

//Using Factory Pattern with implicit object
// Make the following code work:



var Bucket = function (bucket_id) {
    var bucket = document.getElementById(bucket_id);

    var handler = function (e) {
        e.preventDefault(); //stop browser from doing default action, like route to a page listed in a url
        if (e.stopPropagation) {
            e.stopPropagation(); //stop bubbling up the event
        }
        //bucket.appendChild(e.target); or
        bucket.appendChild(e.target);
        e.target.removeEventListener("click", handler);
    };

    var moveOnClick = function (selector) {
        var element = document.querySelector(selector);

        if (element) {

            element.addEventListener("click", handler, true);

        } else {
            console.log("Whoa! Bad Selector: " + selector);
        }
    };

    return {
        moveOnClick: moveOnClick
    };
};

// To make this code work:
var bucket = Bucket("bucket");
bucket.moveOnClick(".main li:nth-child(2)");
bucket.moveOnClick("#articles .flag");
bucket.moveOnClick(".footer div div div div");