Issue
I have my like and dislike buttons which you can toggle but I would like to know how to use local storage to make it have the same position when I refresh the page
If anyone can help me with this
Thanks
the code is attached below
var btn1 = document.querySelector('#green');
var btn2 = document.querySelector('#red');
btn1.addEventListener('click', function() {
if (btn2.classList.contains('red')) {
btn2.classList.remove('red');
}
this.classList.toggle('green');
});
btn2.addEventListener('click', function() {
if (btn1.classList.contains('green')) {
btn1.classList.remove('green');
}
this.classList.toggle('red');
});
body{
margin: 40px;
}
button{
cursor: pointer;
outline: 0;
color: #AAA;
}
.btn:focus {
outline: none;
}
.green{
color: green;
}
.red{
color: red;
}
<script src="https://use.fontawesome.com/fe459689b4.js"></script>
<button class="btn" id="green"><i class="fa fa-thumbs-up fa-lg" aria-hidden="true"></i></button>
<button class="btn" id="red"><i class="fa fa-thumbs-down fa-lg" aria-hidden="true"></i></button>
Solution
Try this.
const btn1 = document.querySelector('#green');
const btn2 = document.querySelector('#red');
const likeStatus = localStorage.getItem('like-status');
if (likeStatus) {
if (likeStatus === 'liked') {
btn1.classList.add('green');
}
if (likeStatus === 'disliked') {
btn2.classList.add('red');
}
}
btn1.addEventListener('click', () => {
setButtonColorAndAddToLocalStorage(btn1, 'green', btn2, 'red', 'liked');
});
btn2.addEventListener('click', () => {
setButtonColorAndAddToLocalStorage(btn2, 'red', btn1, 'green', 'disliked');
});
setButtonColorAndAddToLocalStorage = (elm, elmClass, altElm, altElmClass, status) => {
const elmStatusSet = elm.classList.contains(elmClass);
elm.classList.toggle(elmClass);
altElm.classList.remove(altElmClass);
localStorage.setItem('like-status', elmStatusSet ? '' : status);
};
Answered By - naveen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.