mercredi 2 décembre 2015

Randomly shuffle existing Document Fragment before appending to DOM with JavaScript

I have a dynamically generated text area and button via javascript. I have it working so that when a value is entered into the text area, and then the button is clicked, a random amount of SPAN tags will be created. For each character of the value from the text area, a span tag with the attribute hidden is created.

Here's a working fiddle: http://ift.tt/1PyfmYD

Using JavaScript, I append these spans to a document fragment. If I append the document fragment to a container, all spans in order appended to the DOM. What I want is to "scramble" the document fragment, THEN append it to the DOM.

What I have now when HELLO is typed into the text area and button is clicked:

    <div id="mainContainer">
        <span hidden>H</span>
        <span hidden>E</span>
        <span hidden>L</span>
        <span hidden>L</span>
        <span hidden>O</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
    </div>

What I WANT:

    <div id="mainContainer">
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span hidden>H</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span hidden>E</span>
        <span>Q</span>
        <span>Q</span>
        <span hidden>L</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span hidden>L</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span hidden>O</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
        <span>Q</span>
    </div>




Aucun commentaire:

Enregistrer un commentaire