DEV Community

anderu
anderu

Posted on • Updated on

JS to style radio button list

meme picker website from Scrimba

cat meme

  • Today I learn to create meme picker from Scrimba. User can pick a cat emotion from the 'select your current emotion' list and optional choose 'animated GIFs only' then a random cat meme will show up.

  • The part I want to highlight from this tutorial is where it style the radio button with the use of 'change' event and getElementsByClassName.

emotionRadios.addEventListener('change', highlightCheckedOption)

function highlightCheckedOption(e){
    const radios = document.getElementsByClassName('radio')
    for (let radio of radios){
        radio.classList.remove('highlight')
    }
    document.getElementById(e.target.id).parentElement.classList.add('highlight')
}
Enter fullscreen mode Exit fullscreen mode
  • First, the 'emotionRadios' div which hold all radios button list addEventListener for 'change'.

  • Then we select all radio button with document.getElementsByClassName('radio') which provide list of array of radio button.

  • for of method use to loop thru the radio button and remove class of 'highlight'.

radioItems += `
        <div class="radio">
            <label for="${emotion}">${emotion}</label>
            <input
            type="radio"
            id="${emotion}"
            value="${emotion}"
            name="emotions"
            >
        </div>`
Enter fullscreen mode Exit fullscreen mode
  • Above show the radio button HTML code to create a radio button. When the radio button is click, we want to add class of 'highlight' to the 'radio' div. So we use document.getElementById(e.target.id).parentElement.classList.add('highlight') .
function getMatchingCatsArray(){     
    if(document.querySelector('input[type="radio"]:checked')){
        const selectedEmotion = document.querySelector('input[type="radio"]:checked').value
        const isGif = gifsOnlyOption.checked

        const matchingCatsArray = catsData.filter(function(cat){

            if(isGif){
                return cat.emotionTags.includes(selectedEmotion) && cat.isGif
            }
            else{
                return cat.emotionTags.includes(selectedEmotion)
            }            
        })
        return matchingCatsArray 
    }  
}
Enter fullscreen mode Exit fullscreen mode
  • Beside this, the tutorial also show the use of powerful querySelector which can be to use to select #id, .class and 'element' like const selectedEmotion = document.querySelector('input[type="radio"]:checked').value.

  • filter and includes method is useful to filter the data and loop thru the array of object and then includes will check the exact value in the list of item or object value and lastly provide the match value object list only.

Eat, sleep, code, repeat!
Andrew Tan

Top comments (0)