I was wondering, is it possible to change the attached stylesheet using JavaScript?
For example:
Add an id to the link tag and use
<link id="myStyleSheet" href="stylesheet.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function styler(attr){
var href;
switch(attr){
case'1':href = "stylesheet1.css";break;
case'2':href = "stylesheet2.css";break;
case'3':href = "stylesheet3.css";break;
case'4':href = "stylesheet.css";break;
default:;break;
}
document.getElementById('myStyleSheet').href = href;
}
</script>
See this post
It should be easy:
<html>
<head>
<link rel="stylesheet" href="/tmp/default.css" id="default">
</head>
<body>
<button id="bt">change style</button>
<script>
var targetStyle = document.querySelector('#default'),
otherStyle = '/tmp/style2.css';
document.querySelector('#bt').onclick = function(){
targetStyle.href=otherStyle;
};
</script>
</body>
</html>
Try it
<!DOCTYPE html>
<html>
<head>
<link id="pagestyle" rel="stylesheet" type="text/css" href="default.css">
<script>
function swapStyleSheet(sheet){
document.getElementById('pagestyle').setAttribute('href', sheet);
}
</script>
</head>
<body>
<h2>Javascript Change StyleSheet Without Page Reload</h2>
<button onclick="swapStyleSheet('dark.css')">Dark Style Sheet</button>
<button onclick="swapStyleSheet('blue.css')">Blue Style Sheet</button>
<button onclick="swapStyleSheet('default.css')">Default Style Sheet</button>
</body>
</html>
Another option is to toggle the disabled
property of the link DOM element. According to Mozilla the disabled
HTML attribute is non-standard, but the javascript property is. So if you're toggling it with JS you should be fine.