Pregunta

Consider my actual code: `

    var ck_color = $.cookie('color_cookie');

    var new_css = ".wrap{ \
    color: " + ck_color + "; \
    } \
    ";
    $('body').append('<style id="inline_css" type="text/css">' + new_css + '</style>');


    $('.box-color').each(function() {
        $(this).on('click', function() {
            $('.box_color').removeClass('active');
            $(this).addClass('active');

            var ck_color = $(this).data('color');
            $.cookie('color_cookie', ck_color, { path: '/' });
            if ($("#inline_css").length > 0) {
                $("#inline_css").remove();
            }

            var new_css = ".wrap{ \
            color: " + ck_color + "; \
            } \
            ";
            $('body').append('<style id="inline_css" type="text/css">' + new_css + '</style>');
        });
    });`

My problem is if the inline css grows to many lines, then I have to double it each time, once for the set cookie on the click event, and rewrite it again for the retrieve cookie part earlier in the code. Is there a way to have it written only one time with a similar way? Any better way would be much appreciated.

¿Fue útil?

Solución

var sElement = $('<style id="inline_css" type="text/css"></style>');
$('body').append(sElement);

function updateCSS(color) {
    var new_css = ".wrap{ color: " + color + ";}";
    sElement.html(new_css);
}

Now you should be abel to call the function "updateCSS()" as needed to update the style element.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top