How to make a html javascript like button

Hello,
So the idea is a button that changes text from unliked to liked and stays that way when the page is refereshed. I have no backend, this is a servleress app. Any possible solutions? Thanks.

Yeah. That’s fairly simple.

<button id="like-btn" />
const elm = document.getElementById('like-btn')
const cachedText = window.localStorage.getItem('likeBtnStateText') || 'Please Like'

elm.innerHTML = cachedText

elm.addEventListener('click', e => {
    e.preventDefault()
    const newText = 'Thanks for Liking!'
    
    elm.innerHTML = newText
    window.localStorage.setItem('likeBtnStateText', newText)
    // do some other stuff
})

Demo: https://jsfiddle.net/pbn7wu4h/1/

This will stay as long as the use user hasn’t cleared their cache.

1 Like

@mawburn thank you so much

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.