Search code examples
jquerygoogle-chrome-extensionlocal-storagebackground-position

use local storage to store image background position with jquery for chrome extension


So, when I click a button what should happen is the background image center's itself, and then when I click it again it sets the background position to unset. However, my issue is that I need the user's background position choice to stay and not reset back to unset.

Here is my html button:

<input type="button" id="centerImgBackground" value="Center Image" name="background-image-center">

Here is my Jquery/JS:

window.onload=function(){
  isImgNotCentered = true;  
  localStorage.setItem("toCenter","center center");                                                                 
  localStorage.setItem("unCenter","unset");                                                               
  $("#centerImgBackground").click(function(){                                                                                                                                      
    if(isImgNotCentered){                                                               
      $('body').css('background-position', localStorage.getItem("toCenter"));                                                                            
      isImgNotCentered = false;                                                                            
   }                                                                       
   else {                                                                                                                  
      $('body').css('background-position',localStorage.getItem("unCenter"));

      isImgNotCentered = true;                                                                                                                                             
   }                                                                                                                                             
 });

}

Solution

  • Short and easy:

    $(document).ready(function(){
        localStorage.setCentered == 'center' && $('body').css('background-position','center center');
    
        $('#centerImgBackground').on('click', function(){
            localStorage.setCentered == 'center'? 
                 ($('body').css('background-position','unset'),
                 localStorage.setCentered = 'unset') :
                 ($('body').css('background-position','center center'),
                 localStorage.setCentered = 'center');
        });
    });