Apply CSS dynamically with JavaScript
Using Jquery
Use the css() function to apply style to existing elements where you pass an object containing styles :
var styles = {
backgroundColor : "#ddd",
fontWeight: ""
};
$("#myId").css(styles);
You can also apply one style at the time with :
$("#myId").css("border-color", "#FFFFFF");
Vanilla JS :
var myDiv = document.getElementById("#myId");
myDiv.setAttribute("style", "border-color:#FFFFFF;");
With Css :
You can also use a separate css file containing the different styles needed inside classes, and depending on the context you add or remove those classes to your elements.
in your css file you can have classes like
.myClass {
background-color: red;
}
.myOtherClass {
background-color: blue;
}
Again using jquery, to add or remove a class to an element, you can use
$("#myDiv").addClass('myClass');
or
$("#myDiv").removeClass('myClass');
Again, you can also do the same with vanilla JS:
document.getElementById("#myId").classList.add('myClass')
or
document.getElementById("#myId").classList.remove('myClass')
I think this is a cleaner way as it separates your style from your logic. But if the values of your css depends from what is returned by the server, this solution might be difficult to apply.
How to dynamically create CSS class in JavaScript and apply?
Here is an option:
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);
document.getElementById('someElementId').className = 'cssClass';
Dynamically add rules to CSS file
var style = document.createElement('style');
style.innerHTML = '*{ color:red; } /* put your stuff here */';
document.body.appendChild(style);
create new style element and use it
just test at SO ( run from console ) and it works
document.styleSheets[0].insertRule('* { color: red; }')
javascript beginner: add a dynamic style in javascript?
Your code is fine.But i think that you are not calling it on right time, so call it when your body tag is loaded
window.addEventListener('DOMContentLoaded',function(){
var sheet = document.createElement('style');
sheet.type="text/css";
sheet.innerHTML = "body{color:red;}";
document.body.appendChild(sheet);
}, false);
Add css to head and refresh it dynamically with javascript
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.
Dynamically Switching CSS Files
First, start by defining the original style like this:
HTML:
<link id="style" rel="stylesheet" type="text/css" href="style.css" />
Notice the id=style
that we'll use to find the element. That might fix your first error.
For the second one, you have to decide whether to use document.addEventListener( 'DOMContentLoaded', bindEvents, false );
or window.onload
because they're different functions. This might help you window.onload vs. body.onload vs. document.onready.
So, now we can do some Javascript:
HTML (the links):
<li><button onclick='setStyle("css/style.comicsans.css")'>JB's Fav Font</button></li>
<li><button onclick='setStyle("css/style.other.css")'>Other Font</button></li>
First, notice that I'm only using a parameter to call setStyle
function on click, and btw it's better to work with <button>
, this way we get a cleaner result.
Javascript:
var cssStyle = document.getElementById('style');
window.onload = function(){
if(localStorage && localStorage.getItem("style"))
cssStyle.href = localStorage.getItem("style");
};
function setStyle(newStyle){
cssStyle.href = newStyle;
if(localStorage)
localStorage.setItem("style", newStyle);
};
BONUS:
But if you are only be using two styles, then try to simplify, and do a shorthand method to do this:
HTML:
<li><button onclick='toggleStyle()'>Toggle</button></li>
<!-- cssswitcher js -->
<script type='text/javascript'>
var cssStyle = document.getElementById('style');
var listStyles = ["css/style.comicsans.css", "css/style.other.css"];
window.onload = function(){
if(localStorage && localStorage.getItem("style"))
cssStyle.href = localStorage.getItem("style");
};
function toggleStyle(){
var previousStyle = cssStyle.href;
if(previousStyle.endsWith(listStyles[0]))
newStyle = listStyles[1];
else
newStyle = listStyles[0];
cssStyle.href = newStyle;
if(localStorage)
localStorage.setItem("style", newStyle);
};
</script>
Adding css href link Dynamically in header
console.log(window.location.origin)
How to load up CSS files using Javascript?
Here's the "old school" way of doing it, which hopefully works across all browsers. In theory, you would use setAttribute
unfortunately IE6 doesn't support it consistently.
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://website.example/css/stylesheet.css';
link.media = 'all';
head.appendChild(link);
}
This example checks if the CSS was already added so it adds it only once.
Put that code into a JavaScript file, have the end-user simply include the JavaScript, and make sure the CSS path is absolute so it is loaded from your servers.
VanillaJS
Here is an example that uses plain JavaScript to inject a CSS link into the head
element based on the filename portion of the URL:
<script type="text/javascript">
var file = location.pathname.split( "/" ).pop();
var link = document.createElement( "link" );
link.href = file.substr( 0, file.lastIndexOf( "." ) ) + ".css";
link.type = "text/css";
link.rel = "stylesheet";
link.media = "screen,print";
document.getElementsByTagName( "head" )[0].appendChild( link );
</script>
Insert the code just before the closing head
tag and the CSS will be loaded before the page is rendered. Using an external JavaScript (.js
) file will cause a Flash of unstyled content (FOUC) to appear.
Related Topics
Changing the Key Name in an Array of Objects
How to Reset (Clear) Form Through JavaScript
Http Head Request in JavaScript/Ajax
Responsive Horizontal Page Sliding
Need to Find Height of Hidden Div on Page (Set to Display:None)
Jquery: How to Listen for Dom Changes
Getmonth in JavaScript Gives Previous Month
How to Change an Element Type Using Jquery
Why How to Access Typescript Private Members When I Shouldn't Be Able To
How to Mute All Sound in a Page with Js
Python Library for Rendering HTML and JavaScript
Angular2 Router 2.0.0 Not Reloading Components When Same Url Loaded with Different Parameters
Can JavaScript Access a Filesystem
Prevent Redirection of Xmlhttprequest
Formatting the Date Time with JavaScript