Skip to content Skip to sidebar Skip to footer

2 Questions / 1. Fullscreen(jquery) / 2. Background Change And Save As Cookies

Hello, i searched around the web, but can't find right peace of codes.. I want to do: - go to Fullscreen mode on a button click. - change a background color to dark and save it as

Solution 1:

You can set a cookie value, like this:

document.cookie = "theme=black";

Or, if you want to keep other settings, then:

functionchangeCookieValue(attribute, value) {
    var previousCookie = document.cookie.split(";");
    for (var i = 0; i < previousCookie.length; i++) {
        var key = previousCookie[i].substring(0,previousCookie[i].indexOf("="));
        if (key === attribute) {
            previousCookie[i] = attribute + "=" + value;
            document.cookie = previousCookie.join(";");
            return;
        }
    }
    document.cookie = document.cookie + ";" + attribute + "=" + value;
}

And you can use it like this:

`changeCookieValue("black");`

This is how you can read from cookie:

functiongetCookieValue(attribute) {
    var previousCookie = document.cookie.split(";");
    for (var i = 0; i < previousCookie.length; i++) {
        var key = previousCookie[i].substring(0,previousCookie[i].indexOf("="));
        if (key === attribute) {
            return presiousCookie[i].substring(previousCookie[i].indexOf("=") + 1);
        }
    }
    return"";
}

You can set the class of the body, like this:

$("body").addClass(getCookieValue("theme"));

just make sure that body is already loaded when you run this part. You can design the themes like this:

.black > div {
    background: #000000;
}

.white > div {
    background: #fff;
}

Alternatively, you can work with localStorage, which is much more handy. As about full screen mode, there is no reason to reinvent the wheel, since there is a good fullscreen API you should use for this purpose.

And you can make sure that changeCookieValue runs with the proper parameter on click using the onclick attribute of your radio buttons.

Alternatively, you might consider storing the values inside a database and adding the needed class to body on server, when you generate it.

EDIT:

You can add the class at the loaded event:

$(function() {
    $("body").addClass(getCookieValue("theme"));
});

Note, that this will be responsible to display the theme at page load. You need to display it whenever you call changeCookieValue for theme. Before you call that function$("body").removeClass(getCookieValue("theme")); and after the function is executed $("body").addClass(getCookieValue("theme")); (note, that the theme is changed). Naturally, you need a wrapper for this:

functionchangeTheme(theme) {
    $("body").removeClass(getCookieValue("theme"));
    changeCookieValue("theme", theme);
    $("body").addClass(getCookieValue("theme"));
}

and trigger this changeTheme at your radio buttons.

Post a Comment for "2 Questions / 1. Fullscreen(jquery) / 2. Background Change And Save As Cookies"