The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript appending stylesheet on window resize

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
  • #176259

    Im appending a stylesheet on window resize with jquery to add styles when the window is bellow a certain width. Yes i could use media queries but thats not the point and its not possible in my situation.

           $(window).resize(function() {
               if ($(window).width() < 1000) {
           $("head".append("<link rel="stylesheet" type="text/css" href="css/page.css"/>

    The problem is that it keeps appending the stylesheet like a hundred times because the window is bellow the width. I have a few ideas on how to fix this but i want the best method. So how can i append the stylesheet only once when the window width is bellow the width? or is it no big deal if it appends the stylesheet multiple times?


    Here is hot FitVids.js does it.

    if(!document.getElementById('fit-vids-style')) {
          // appendStyles:
          var head = document.head || document.getElementsByTagName('head')[0];
          var css = '.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}';
          var div = document.createElement('div');
          div.innerHTML = '<p>x</p><style id="fit-vids-style">' + css + '</style>';

    Well… if you really CAN’T use media queries, then I wouldn’t go the route you’re trying to go.

    The biggest problem after attaching a styling sheet, is removing it when sized back up.

    What I would do instead which is much easier is on window resize change a class on the html or body tag. For example: sm, med, lrg, xl.

    That way, you can have ALL your css on the same style sheet and target different sizes

    div {
    } div {


    Thats a great idea, but ive already been doing it and its working perfectly both when adding and removing the stylesheet. I guess i could do the class thing you mentioned.

Viewing 4 posts - 1 through 4 (of 4 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.