Home > Software engineering >  jQuery add class to body when localStorage
jQuery add class to body when localStorage

Time:04-08

We use the following JS code to check localStorage and save this.

require(["jquery"], function (e) {
    const t = function () {
        const t = e("#togglebtw").is(":checked");
        e(".price-container .price-including-tax").toggle(!t), e(".price-container .price-excluding-tax").toggle(t), localStorage.setItem("togglebtw", t ? "true" : "false");
    };
    e(function () {
        e("#togglebtw")
            .on("click", t)
            .prop("checked", "true" === localStorage.getItem("togglebtw")),
            t();
    });
});

How can we also add/remove a class to the body when the #togglebtw is checked?

CodePudding user response:

You can toggle a class to the body at any time with this code, example using btwChecked as the class.

e("body").toggleClass("btwChecked", "true" === localStorage.getItem("togglebtw")) 

or, using the checkbox:

e("body").toggleClass("btwChecked", e("#togglebtw").is(":checked"))

(where e would normally be $ for jquery)

as you already have t = e("#togglebtw").is(":checked") this becomes e("body").toggleClass("btwchecked", t) after that t =.

This uses an overload of toggleClass(className, state) which allows you to pass in a bool to determine if the class should be added or removed.

To add this to your existing code:, in a similar, mini-fied manner:

require(["jquery"], function (e) {
    const t = function () {
        const t = e("#togglebtw").is(":checked");
        e(".price-container .price-including-tax").toggle(!t), 
        e(".price-container .price-excluding-tax").toggle(t),
        localStorage.setItem("togglebtw", t ? "true" : "false"),
        e("body").toggleClass("btwChecked", t);
    };
    e(function () {
        e("#togglebtw")
            .on("click", t)
            .prop("checked", "true" === localStorage.getItem("togglebtw")),
        t();
    });
});

There's no need to change the doc.ready function as this calls t()

  • Related