Home › Forums › JavaScript › appending stylesheet on window resize
- This topic is empty.
-
AuthorPosts
-
July 23, 2014 at 4:24 pm #176259AnonymousInactive
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?
July 23, 2014 at 4:33 pm #176260JacobPetersParticipantHere is hot FitVids.js does it.
if(!document.getElementById('fit-vids-style')) { // appendStyles: https://github.com/toddmotto/fluidvids/blob/master/dist/fluidvids.js 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>'; head.appendChild(div.childNodes[1]); }
July 23, 2014 at 6:39 pm #176268noahgelmanParticipantWell… 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 {
background:blue;
}html.sm div {
background:red;
}July 24, 2014 at 4:15 pm #176372AnonymousInactiveThats 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.
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.