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?
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.
I think the best way to do this is someting like:
In my hones opinion parsing the text content of the of a style tag would be more complex and slower.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With