Frage

I'm testing javascript code for day/light background switch and I don't know how to do something. I'm newbie to javascript, so I'm learning new stuff.

So what I want to do?
When I click for example on button "Day" (which change background to yellow), I want that style for yellow background stay in the code after page is refreshed. I heard something about Cookies/LocalStorage, but I don't know how to implement it for this code.

Feel free to change whole code if you know easier way to do this, but please explain why it's better or why it should be like that.

Thanks in advance for your help.


Here is the code:

HTML:

<body id="body">
    <input type="button" onclick="day();" value="Day" />
    <input type="button" onclick="night();" value="Night" />
    <input type="button" onclick="reset();" value="Reset" />   
</body>

CSS:

.darkSwitch {
  background: #808080;
}
.lightSwitch {
  background: #ffff99;
}

JavaScript:

function day() {
    body.className = "lightSwitch";
};
function night() {
    body.className = "darkSwitch";    
};
function reset() {
    body.className = "";
};

$(function() {
    var button = $('input[type=button]');
    button.on('click', function() {
        button.not(this).removeAttr('disabled');
        $(this).attr('disabled', '');
    });
});
War es hilfreich?

Lösung

Last edit: now disabling selected button on page load, CODE NOT IN THIS POST, see the latest JSFiddle

Explanation

What I did:

  • The code is put in between<script> tags at the end of the <body> (personnal preference)
  • I added the parameter event to the onClick event of the button element.
  • I added event.preventDefault() at the start of the onclick event of the button element: ensuring the page is NOT refreshed on the click of a button.

Warning: ALL the buttons will behave the same in your page. If you have other buttons, I suggest you add another class for those three buttons and bind the event on the button.myClass element.

  • I added a condition on the button state change, so the reset button won't get disabled.
  • eval($(this).val().toLowerCase()+"();"); gets the value of the the clicked button and executes the function attached to it.

Solution

HTML

<body id="body">
    <input type="button" class="changeBg" onclick="day();" value="Day" />
    <input type="button" class="changeBg" onclick="night();" value="Night" />
    <input type="button" class="changeBg" onclick="reset();" value="Reset" />
</body>

JavaScript

(JSFiddle) <-- Check this out Updated with classes & cookies

function day() {
    body.className = "lightSwitch";
};

function night() {
    body.className = "darkSwitch";
};

function reset() {
    body.className = "";
};

$(function () {
    /* RegEx to grab the "bgColor" cookie */
    var bgColor = document.cookie.replace(/(?:(?:^|.*;\s*)bgColor\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    
    var button = $('input[type=button].changeBg');
    button.on('click', function (event) {
        event.preventDefault();
        
        /* Executing the function associated with the button */
        eval($(this).val().toLowerCase() + "();");

        button.not($(this)).removeAttr('disabled');
        if ($(this).val() != "Reset") {
            $(this).attr('disabled', '');
            
            /* Here we create the cookie and set its value, does not happen if it's Reset which is fired. */
            document.cookie = "bgColor="+$(this).val();
        }
    });
    
    /* If the cookie is not empty on page load, execute the function of the same name */
    if(bgColor.length > 0)
    {     
        eval(bgColor.toLowerCase()+'()');
         
        /* Disable the button associated with the function name */
        $('button[value="'+bgColor+'"]').attr("disabled","disabled");
    }
});

Andere Tipps

I recommend you don't use cookies unless localStorage is not supported. They slow your site down.

if(localStorage){

   localStorage.setItem("bgColor", "lightSwitch");

}else{

   document.cookie = "bgColor=lightSwitch";

}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top