0

I'm having trouble inserting a new CSS rule with Javascript in order to adjust the width of a display block with a fixed position to the width of the window. Could someone explain why this isn't working? Here's the jsfiddle for the HTML, CSS, and Javascript (along with a bit of jQuery) involved: http://jsfiddle.net/b9knL/ and this is the Javascript in question:

$(function () {
                function change_header(){ 
                     var sheets = document.styleSheets;
                     var sheet = document.styleSheets[0];
                     var mywidth = $(window).width();
                     var selector = "header{ width: "+mywidth+"; }";
                     sheet.insertRule(selector, index);
                }
                change_header();

                $(window).resize(function() {
                        change_header();
                });
});
3
  • 1
    The scroll event happens a few hundred times when you scroll down a page, and you're inserting a new Rule every time, you're sure you've added enough of those ? Commented Apr 24, 2014 at 22:54
  • Sorry, that was a filler from an old function that I was using to make the header fixed, I will be changing that to a jQuery function that enables itself whenever the window size is changed. Commented Apr 24, 2014 at 22:55
  • index is undefined - add var index=0; to fix. also specify px for width. var selector = "header { width: "+mywidth_+"px; }"; Commented Apr 24, 2014 at 23:06

1 Answer 1

1

Since it is position:fixed just add width:100% to the css rule and it will auto adjust on its own..

header{
    background-color: #005e00;
    display: block;
    position: fixed;
    z-index: 500;
    width:100%;
    box-shadow: 0px 5px 5px #888888;
}

no need for scripting..

Demo at http://jsfiddle.net/b9knL/2/

Sign up to request clarification or add additional context in comments.

1 Comment

Well that was a much simpler answer than I expected! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.