Save click on localStorage

Asked

Viewed 85 times

0

I have a simple button that when clicked its text changes - and when clicked again it goes back to the previous text. So:

<button class="texto">texto 1</button>

<scprit>
    $('.texto').click(function(){
        var $this = $(this);
        $this.toggleClass('texto');
        if($this.hasClass('texto')){
            $this.text('texto 1');          
        } else {
            $this.text('texto 2');
        }
    });
</scprit>

I need you to be saved in localStorage, when the user reloads the page is still in the last way he clicked. Help me out, please!

1 answer

1


Oops, try it this way:

<button class="texto">texto 1</button>

$( document ).ready(function() {
  var savedText = localStorage.getItem('click');

  if(savedText) {
    $('.texto').text(savedText);
  }
});

$('.texto').click(function(){
    var $this = $(this);
    $this.toggleClass('texto');
    if($this.hasClass('texto')){
        $this.text('texto 1');
    } else {
        $this.text('texto 2');
    }
    localStorage.setItem('click', $this.text());
});
  • aeee! guy who understands is fucking dms hehe. thank you!!

  • I saw that if I use more than one button with the same class, clicking changes only it. However, all the others are saved in localStorage because when I reload the page all have the same value of that one clicked. Would you know how to save only that (this) one? or would it be necessary to create such a system for each one? (and I have muuuitos buttons with the same effect, it would be terrible kkkk)

  • Work with ID and not with class to prevent this, to use ID in Jquery, use # instead of .

  • the problem is that would not take the various classes that is necessary, would have to make one by one...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.