Set entire page's css on click? - javascript

Does anyone know how I can change the entire document's CSS file on click? I've searched around but only found a few results on setting a class/ID's CSS, not the entire document. My website has two themes, light/dark, and I want to load up "light.css" or "dark.css" from two links.
Thanks.

You need to change the src of the the link tag, which controls the styles. For example, you probably have this in your head tag:
<link rel="stylesheet" href="light.css">
You need to change the href attribute of the link tag to "dark.css" when you click something. You can do that like this:
document.getElementById('id-of-element').addEventListener('click',function(){
document.getElementsByTagName('link')[0].setAttribute('href',isDark?'light.css':'dark.css');
isDark=isDark?false:true;
}
IMPORTANT: you need to set isDark to false or true before this code, depending on whether the page is supposed to be dark or light in the beginning. You also need to change id-of-element to the id of the element that should be clicked to toggle the state of the page.
I think this is better than the other answers because it is simpler and uses no jquery.
EDIT: I accidentally had the src attribute instead of the href one before. I now updated it to be correct.

Yeah, you can do using theming. But the changing of CSS is limited to the <body> tag.
$("a.theme").click(function(){
$("body").addClass("dark");
});
I have used jQuery library to make the coding easier. And it is not a good idea to switch CSS rather, you can change the classes.
Demo
You can check out the working demo in jsBin.
Check out this answer for more details: Selecting a web page look and feel without reloading, with one CSS.

Try something like this:
Light
Dark
<script type="text/javascript" charset="utf-8">
$('a#light, a#dark').click(function(){
$('style').remove();
$.ajax({
url:'http://www.example.com/' + $this.attr('id') + '.css',
success:function(data){
$('<style></style>').appendTo('head').html(data);
}
})
})
</script>
Of course, you need to load jQuery first.

There's 2 ways that come immediately to mind.
1) Add a style tag to the page's head, ensuring that the style tag has a unique id. You can then set the innerHTML of that element. (somewhat messy)
2) Add a link tag to the page's head, also ensuring that it has a unique id. You set the type='text/css' and the rel='stylesheet' attributes. You the set the src of this link element to the appropriate css file.
Here's an example of each type. Just supply css files for theme3() and theme4() functions.
Example:
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(element, newStr)
{
index=element.className.indexOf(newStr);
if ( index == -1)
element.className += ' '+newStr;
else
{
if (index != 0)
newStr = ' '+newStr;
element.className = element.className.replace(newStr, '');
}
}
function forEachNode(nodeList, func)
{
var i, n = nodeList.length;
for (i=0; i<n; i++)
{
func(nodeList[i], i, nodeList);
}
}
window.addEventListener('load', mInit, false);
function mInit()
{
var style = newEl('style');
style.setAttribute('id', 'dynCss');
document.head.appendChild(style);
var style2 = newEl('link');
style2.setAttribute('type', 'text/css');
style2.setAttribute('rel', 'stylesheet');
style2.setAttribute('id', 'dynCss2');
document.head.appendChild(style2);
}
function theme1()
{
var style = byId('dynCss');
style.innerHTML = "h1{color: red;}";
var style2 = byId('dynCss2');
style2.setAttribute('href', '');
}
function theme2()
{
var style = byId('dynCss');
style.innerHTML = "h1{color: blue;}";
var style2 = byId('dynCss2');
style2.setAttribute('href', '');
}
function theme3()
{
var style = byId('dynCss');
style.innerHTML = "";
var style2 = byId('dynCss2');
style2.setAttribute('href', 'style3.css');
}
function theme4()
{
var style = byId('dynCss');
style.innerHTML = "";
var style2 = byId('dynCss2');
style2.setAttribute('href', 'style4.css');
}
</script>
<style>
</style>
</head>
<body>
<h1>This is the heading</h1>
<input type='button' onclick='theme1();' value='Theme 1'/>
<input type='button' onclick='theme2();' value='Theme 2'/>
<input type='button' onclick='theme3();' value='Theme 3'/>
<input type='button' onclick='theme4();' value='Theme 4'/>
</body>
</html>

Related

Onclick event, print divs. how to Exclude class name

This question is a little add for this Stackoverflow question Here I ended up with this code.
<script type="text/javascript">
//Simple wrapper to pass a jQuery object to your new window
function PrintElement(elem){
var data = '';
$(elem).each(function() {
data = data + $(this).html();
});
Popup(data);
}
//Creates a new window and populates it with your content
function Popup(data) {
//Create your new window
var w = window.open('', 'Print', 'height=400,width=600');
w.document.write('<html><head><title>Print</title>');
//Include your stylesheet (optional)
w.document.write('<link rel="stylesheet" href="add/css/layout.css" type="text/css" />');
w.document.write('<link rel="stylesheet" href="add/css/main.css" type="text/css" />');
w.document.write('</head><body>');
//Write your content
w.document.write(data);
w.document.write('</body></html>');
w.print();
w.close();
return true;
}
</script>
that when i tricker the
onclick="PrintElement('.PrintElement')">Print
I can print out some divs with the class="PrintElement" my question is now...
If i have some elements inside the DIV that i dont want to print out, how can i then add a class="NOprintelement" so the code know that the elements with this class, need to be excluded in the print event ?
Without knowing more details, you should probably try to hide DOM elements using css media queries. For example, if you have a div with class = 'hideWhenPrinting', your CSS could include:
#media print {
.hideWhenPrinting { display: none }
}
See this related question:
How do I hide an element when printing a web page?

onclick does not fire in a link that is created by clicking another link

Javascript function writelink creates a link that fires function hiya. It works when I define and invoke writelink inside script. But, I want the body to contain another link that calls writelink to create a link. This final link fails to fire (but works if I replace hiya with alert). I am a total novice, so I hope it is something obvious. The main idea is that I have to create some links from code, and these have to fire to execute some more code. (If you want me to do this a totally different way, please try to give me a complete example.)
<HTML>
<HEAD>
<script>
function hiya (num){
alert("hiya " + num);
}
function writelink (num){
var htmlstr = "link" + num + "";
document.write(htmlstr);
}
writelink(1);
</script>
</HEAD>
<BODY>
<br>
link2;
<br>
</HTML>
document.write(htmlstr) replaces the entire DOM with the link / htmlstr you are about to insert. Use pure javascript to create the link(s) instead :
function writelink(num){
var link = document.createElement('a');
link.innerHTML='link '+num;
link.href='#';
link.onclick=hiya(num);
document.body.appendChild(link);
}
Just replace writelink() with the code above.
You would typically want to add the link to a certain element instead of just <body>, lets say a <div> with the id menu :
var cnt = document.getElementById('menu');
cnt.appendChild(link);
update
<!doctype html>
<html>
<head>
</head>
<body>
link2
<script>
function hiya(num) {
alert("hiya " + num);
}
function writelink(num){
var link = document.createElement('a');
link.innerHTML='link '+num;
link.href='#';
link.onclick=function(e) {
hiya(num);
}
document.body.appendChild(link);
}
writelink(1);
</script>
</body>
</html>

Switching backgrounds, while switching text

I was able to make the text loop infinitely and the body color change once:
<?php?>
<style type="text/css">
<!--
header{background-color:orange;}
#color1{background-color:red;}
#color2{background-color:green;}
#color3{background-color:blue;}
-->
</style>
<script type="text/javascript">
<!--
var flip = (function() {
var flip = ['_addText1','_addText2','_addText3'];
var count = -1;
return function() {
return flip[++count % flip.length];
}
}());
-->
</script>
<body id="color1">
<header onclick="document.getElementById('click').innerHTML = flip(); document.getElementById('color1').setAttribute('id', 'color2');">
<h1>StaticText<a id="click">_ThisWillChange</a></h1>
<p>Click anywhere in the header to change the text above.<br />
This will also change the body color.</p>
</header>
</body>
<?php?>
The first problem is; if I add more color changes to the 'onclick' attribute it stops working all together. Basically I want the color to loop with the text:
document.getElementById('color2').setAttribute('id', 'color3');
document.getElementById('color3').setAttribute('id', 'color1');
The second problem is that I'm not really 'fluent' in javascript. I'm actually lucky I figured out this much to be honest.
I'm sure there's a way to put it all into the javascript (to keep my HTML clean), but I don't know how.
Any help would be most appreciated! Thanks in advance...
Why do you want to change the id of the element if you are so keen to set the color.
You can just the class on the body element which should get the work done for you.
Secondly it's a bad practice to bind events inline. Use javascript to bind the events as well.
<body id="color1" class="color1">
This is one way of writing the code.
Code
var header = document.getElementsByTagName('header')[0];
header.addEventListener('click', function () {
var body = document.getElementById('color1');
document.getElementById('click').innerHTML = flip("text");
body.className = flip("color");
});
var flip = (function () {
var flip = ['_addText1', '_addText2', '_addText3'],
colors = ["color1", "color2", "color3"];
var count = -1,
colorCount = -1;
return function (arg) {
if(arg === 'text')
return flip[++count % flip.length];
if(arg === 'color')
return colors[++colorCount % colors.length];
}
})();
HTML
<body id="color1" class="color0">
<header>
<h1>StaticText<a id="click">_ThisWillChange</a></h1>
<p>Click anywhere in the header to change the text above.
<br />This will also change the body color.</p>
</header>
</body>
CSS
header {
background-color:orange;
}
.color0 {
background-color:yellow;
}
.color1 {
background-color:red;
}
.color2 {
background-color:green;
}
.color3 {
background-color:blue;
}
Check Fiddle

append child after the node of the script that made the call

When the call bellow is done the class creates a set of elements (a form) and then I want to append them right after the script that called it.
I have been looking at various similar questions but the best of them simply append it after the last script on the page.
It would work nicely in the head but not the body.
<script type="text/javascript">
new exampleClass();
</script>
You should have some type of unique identification to find and append elements after the script. You can use document.getElementById() if you have id, or document.getElementsByTagName("script") to get script elements and get the required script element and then use appendChild()
Ok, here is the horrible hack mentioned.
HTML
<div>Stuff</div>
<script type="text/javascript">
noop();
</script>
<div>More stuff</div>
<script type="text/javascript">
new ExampleClass();
</script>
<div>More stuff</div>
<script type="text/javascript">
noop();
</script>
<div>More stuff</div>
Javascript
function noop() {}
function appendAfter(node, newNode) {
if (node.nextSibling) {
node.parentNode.insertBefore(newNode, node.nextSibling);
} else {
node.parentNode.appendChild(newNode);
}
}
function ExampleClass() {
window.addEventListener("load", function () {
var scripts = document.getElementsByTagName("script"),
div = document.createElement("div"),
length = scripts.length,
i = 0,
script;
div.appendChild(document.createTextNode("Inserted"));
while (i < length) {
script = scripts[i];
if (script.firstChild && script.firstChild.nodeValue.indexOf("ExampleClass()") !== -1) {
appendAfter(script, div);
}
i += 1;
}
}, false);
}
On jsfiddle
Based on some of your comments and some other similar I have thought of doing something like this and it seems to work.
// Generate random string we can use as element id
var rs = Math.random().toString(36).substring(2);;
// Document write an empty div with the above string as id
document.write('<div id="' + rs + '"></div>');
// Get the element to use for append
var ip = document.getElementById(rs);
Please feel free to comment if you think it may have a fatal flaw.

Javascript Onclicks not working?

I have a jQuery application which finds a specific div, and edit's its inner HTML. As it does this, it adds several divs with onclicks designed to call a function in my JS.
For some strange reason, clicking on these never works if I have a function defined in my code set to activate. However, it works fine when calling "alert("Testing");".
I am quite bewildered at this as I have in the past been able to make code-generated onclicks work just fine. The only thing new here is jQuery.
Code:
function button(votefor)
{
var oc = 'function(){activate();}'
return '<span onclick=\''+oc+'\' class="geoBut">'+ votefor +'</span>';
}
Elsewhere in code:
var buttons = '';
for (var i = 2; i < strs.length; i++)
{
buttons += button(strs[i]);
}
var output = '<div name="pwermess" class="geoCon"><div class="geoBox" style=""><br/><div>'+text+'</div><br/><div>'+buttons+'</div><br/><div name="percentages"></div</div><br/></div>';
$(obj).html(output);
Elsewhere:
function activate()
{
alert("Testing");
}
You may want to take a look at jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:
$(".somebtn").live("click", myClickHandler);
Follows a dummy example, may be this can help you.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
c="Hello world";
$("#output").html(c);
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>
Change this:
var oc = 'function(){activate();}'
To be this instead:
var oc = 'activate();'

Categories

Resources