Geek Logbook

Tech sea log book

50projectsIn50days – Day 13: Random Picker

A text area where you add a number of elements divided by comma. Then, when you press enter the you’ll see a simple animation and a, in yellow, the chosen one.

The text area in index.html is where you’ll add the text

<textarea placeholder="Enter choices here..." id="textarea"></textarea>

And the relevant Style are related with the elements: tag and tag.higlight

.tag {
    background-color: #000000;
    color: white;
    border-radius: 50px;
    padding: 10px 20px;
    margin: 0 5px 10px 0;
    font-size: 14px;
    display: inline-block;
}

.tag.highlight {
    background-color: #F9ED69;
    color: black
}

Let’s jump to the Javascript because where all the interactivity happens:

  • The selection
  • The interactivity animation.

The event Listener inside the script.js has an event listener where the texts are added inside them we can find two custom functions: createTags(input) and randomSelect() this event is listening for a ‘keyup’ envent. It’s event is fired whe

The keyup event is fired when a key is released.

Element: keyup event

Before press enter you can create as Tags as you want. But after you press this one, you Will pass the line where CreateTags is, and start working on the random Selection of the workd.

textarea.addEventListener('keyup', (e) => {
    createTags(e.target.value)

    if(e.key === 'Enter') {
        setTimeout(() => {
            e.target.value = ''
        }, 10)

        randomSelect()
    }
})

The createTags Functions is quite straigthforward for the input you add to the input element the function will split by a delimiter (‘,’), discard the extra spaces and add the class tag, so the CSS style impact in the visualization. Then append the tag element to the Tags Elements in the innerHTML

function createTags(input) {
    const tags = input.split(',').filter(tag=> tag.trim() !== '').map(tag => tag.trim())

    tagsEl.innerHTML = ''

    tags.forEach(tag => {
        const tagEl = document.createElement('span')
        tagEl.classList.add('tag')
        tagEl.innerText = tag
        tagsEl.appendChild(tagEl)
    })
}

Once the tags are added to the DOM is time to pick the ones that will Win. But, despite of being named as randomSelect the function which properly pick the element is the pickRandomTagFunction wich select one tag fro the tags.

function pickRandomTag(){
    const tags = document.querySelectorAll('.tag')
    return tags[Math.floor(Math.random() * tags.length)]
}

Therefore the randomSelect() function is the responsible of set the highligth and the unhiglight working as a wrapper. It’s an intesreting way to create functionalities but maybe is not the core.

You can see the code in this GitHub Repository: 13.random_picker and the demo of the project is here: Random Picker

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*