Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add css to head and refresh it dynamically with javascript

I try to add a css rule dynamically by javascript and then update css on scroll event.

This is my code:

var head = document.head || document.getElementsByTagName('head')[0],
        createElement = document.createElement('style');
    // append style to head
    head.appendChild(createElement); 

    // scroll event
    $(window).on('scroll touchmove', function(e) {
        // define variables 
        var body = $('body'),
            style = {
                waY: $(document).scrollTop()
            };
        // create css rules
        var css = 'body:before {';
            css += 'background-position: 0px ' + (style.waY*0.4).toFixed(2) + 'px';
            css += '}';
            css += 'body:after {';
            css += 'background-position: 0px ' + (style.waY*0.4).toFixed(2) + 'px';
            css += '}';

        createElement.innerHTML = '';
        // add css rules to style tag
        if (css.styleSheet) {
            // If IE
            createElement.styleSheet.cssText = css;
        } else {
            // Other browsers
            createElement.appendChild(document.createTextNode(css));
        } 
    });

I don't like this code because it overloads the page and it work slowly. How each time clear the style or just overload existing rules?

If there're any other way to reload css inside style?

like image 729
Constantine Golub Avatar asked Feb 04 '26 09:02

Constantine Golub


2 Answers

This is all you need, it will change the background-position in runtime.

$(window).on('scroll touchmove', function(e) {
    var newposition = ($(document).scrollTop() * 0.4).toFixed(2);
    $('body').css('background-position', '0px ' + newposition + 'px');
});

Here is an example at jsFiddle.

like image 183
António Almeida Avatar answered Feb 06 '26 23:02

António Almeida


I think the best way to do this is someting like:

  1. Create an array to keep track of all the rules and styles
  2. Overwrite a certain rune in that array
  3. "Publish"/create the style tag with a specific ID and overwrite it every time you need to

In my hones opinion parsing the text content of the of a style tag would be more complex and slower.

like image 43
Valentin D Avatar answered Feb 06 '26 22:02

Valentin D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!