I wondering how I can select the two stylesheet links I have below in the resize function below. I need to modify the two links href value based on the orientation value, but I'm unsure how to select and populate those inside the conditional statement below, any ideas?
<head>
<link rel="stylesheet" href="css/style.css" type='text/css' media='all' />
<link rel="stylesheet" href="css/iphone.css" type='text/css' media='all' />
<script type="text/javascript">
$ = jQuery
$(document).ready(function() {
$(window).resize(function() {
var orientation = window.orientation;
if(orientation == 90 || orientation == -90) {
//populate href of stylesheet link here
} else {
//populate href of stylesheet link here
}
});
});
</script>
</head>
Just give your stylesheet and id and change it like so:
$("#id").attr("href", "/somecss.css");
If you use CSS3 you can use css3 Media Queries to change your styles based on the Orientation of the users browser.
<link rel="stylesheet" media="all and (orientation:landscape)"href="landscape.css">
This will only include this stylesheet if the orientation of the users browser is landscape.
Remember this will only work on CSS3 compatible browsers.
Look at this link :
http://www.1stwebdesigner.com/tutorials/how-to-use-css3-orientation-media-queries/
another SO question:
CSS3: Detecting device orientation for iPhone
Its better to put both the css in one file and not to change the css later on.
Css Gets loaded first . and only then your javascript gets executed. So first your default css will be loadeed. then you would change the href tag (using other answer) then next file would be loaded. making an extra call to server. The better idea it to have both(landscape & potrait) css defined in one file.
IMHO 80% of the css for both landscape & potrait would be the same the rest 20% can be configured using the naive css fomr the first link.
Related
I have a page which has <link> in the header that loads the CSS named light.css. I also have a file named dark.css. I want a button to swap the style of the page all together (there are 40 selectors used in css file and some do not match in two files).
How can I remove reference to light.css with JS and remove all the styles that were applied and then load dark.css and apply all the styles from that? I can't simply reset all of the elements, since some of the styles are applied through different css files and some are dynamically generated by JS. Is there a simple, yet effective way to do that without reloading the page? Vanilla JS is preferable, however I will use jQuery for later processing anyways, so jQ is also fine.
You can include all the stylesheets in the document and then activate/deactivate them as needed.
In my reading of the spec, you should be able to activate an alternate stylesheet by changing its disabled property from true to false, but only Firefox seems to do this correctly.
So I think you have a few options:
Toggle rel=alternate
<link rel="stylesheet" href="main.css">
<link rel="stylesheet alternate" href="light.css" id="light" title="Light">
<link rel="stylesheet alternate" href="dark.css" id="dark" title="Dark">
<script>
function enableStylesheet (node) {
node.rel = 'stylesheet';
}
function disableStylesheet (node) {
node.rel = 'alternate stylesheet';
}
</script>
Set and toggle disabled
<link rel="stylesheet" href="main.css">
<link rel="stylesheet" href="light.css" id="light" class="alternate">
<link rel="stylesheet" href="dark.css" id="dark" class="alternate">
<script>
function enableStylesheet (node) {
node.disabled = false;
}
function disableStylesheet (node) {
node.disabled = true;
}
document
.querySelectorAll('link[rel=stylesheet].alternate')
.forEach(disableStylesheet);
</script>
Toggle media=none
<link rel="stylesheet" href="main.css">
<link rel="stylesheet" href="light.css" media="none" id="light">
<link rel="stylesheet" href="dark.css" media="none" id="dark">
<script>
function enableStylesheet (node) {
node.media = '';
}
function disableStylesheet (node) {
node.media = 'none';
}
</script>
You can select a stylesheet node with getElementById, querySelector, etc.
(Avoid the nonstandard <link disabled>. Setting HTMLLinkElement#disabled is fine though.)
You can create a new link, and replace the old one with the new one. If you put it in a function, you can reuse it wherever it's needed.
The Javascript:
function changeCSS(cssFile, cssLinkIndex) {
var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);
var newlink = document.createElement("link");
newlink.setAttribute("rel", "stylesheet");
newlink.setAttribute("type", "text/css");
newlink.setAttribute("href", cssFile);
document.getElementsByTagName("head").item(cssLinkIndex).replaceChild(newlink, oldlink);
}
The HTML:
<html>
<head>
<title>Changing CSS</title>
<link rel="stylesheet" type="text/css" href="positive.css"/>
</head>
<body>
STYLE 1
STYLE 2
</body>
</html>
For simplicity, I used inline javascript. In production you would want to use unobtrusive event listeners.
If you set an ID on the link element
<link rel="stylesheet" id="stylesheet" href="stylesheet1.css"/>
you can target it with Javascript
document.getElementsByTagName('head')[0].getElementById('stylesheet').href='stylesheet2.css';
or just..
document.getElementById('stylesheet').href='stylesheet2.css';
Here's a more thorough example:
<head>
<script>
function setStyleSheet(url){
var stylesheet = document.getElementById("stylesheet");
stylesheet.setAttribute('href', url);
}
</script>
<link id="stylesheet" rel="stylesheet" type="text/css" href="stylesheet1.css"/>
</head>
<body>
<a onclick="setStyleSheet('stylesheet1.css')" href="#">Style 1</a>
<a onclick="setStyleSheet('stylesheet2.css')" href="#">Style 2</a>
</body>
This question is pretty old but I would suggest an approach which is not mentioned here, in which you will include both the CSS files in the HTML, but the CSS will be like
light.css
/*** light.css ***/
p.main{
color: #222;
}
/*** other light CSS ***/
and dark.css will be like
/*** dark.css ***/
.dark_theme p.main{
color: #fff;
background-color: #222;
}
/*** other dark CSS ***/
basicall every selector in dark.css will be a child of .dark_theme
Then all you need to do is to change the class of body element if someone selects to change the theme of the website.
$("#changetheme").click(function(){
$("body").toggleClass("dark_theme");
});
And now all your elements will have the dark css once the user clicks on #changetheme. This is very easy to do if you are using any kind of CSS preprocessors.
You can also add CSS animations for backgrounds and colors which makes the transition highly smooth.
Using jquery you can definitely swap the css file. Do this on button click.
var cssLink = $('link[href*="light.css"]');
cssLink.replaceWith('<link href="dark.css" type="text/css" rel="stylesheet">');
Or as sam's answer, that works too. Here is the jquery syntax.
$('link[href*="light.css"]').prop('disabled', true);
$('link[href*="dark.css"]').prop('disabled', false);
Using jquery .attr() you can set href of your link tag .i.e
Sample code
$("#yourButtonId").on('click',function(){
$("link").attr(href,yourCssUrl);
});
Maybe I'm thinking too complicated, but since the accepted answer was not working for me I thought I'd share my solution as well.
Story:
What I wanted to do was to include different 'skins' of my page in the head as additional stylesheets that where added to the 'main' style and switch them by pressing a button on the page (no browser settings or stuff).
Problem:
I thought #sam's solution was very elegant but it did not work at all for me. At least part of the problem is that I'm using one main CSS file and just add others on top as 'skins' and thus I had to group the files with the missing 'title' property.
Here is what I came up with.
First add all 'skins' to the head using 'alternate':
<link rel="stylesheet" href="css/main.css" title='main'>
<link rel="stylesheet alternate" href="css/skin1.css" class='style-skin' title=''>
<link rel="stylesheet alternate" href="css/skin2.css" class='style-skin' title=''>
<link rel="stylesheet alternate" href="css/skin3.css" class='style-skin' title=''>
Note that I gave the main CSS file the title='main' and all others have a class='style-skin' and no title.
To switch the skins I'm using jQuery. I leave it up to the purists to find an elegant VanillaJS version:
var activeSkin = 0;
$('#myButton').on('click', function(){
var skins = $('.style-skin');
if (activeSkin > skins.length) activeSkin=0;
skins.each(function(index){
if (index === activeSkin){
$(this).prop('title', 'main');
$(this).prop('disabled', false);
}else{
$(this).prop('title', '');
$(this).prop('disabled', true);
}
});
activeSkin++
});
What it does is it iterates over all available skins, takes the (soon) active one, sets the title to 'main' and activates it. All other skins are disabled and title is removed.
Simply update you Link href attribute to your new css file.
function setStyleSheet(fileName){
document.getElementById("WhatEverYouAssignIdToStyleSheet").setAttribute('href', fileName);
}
I reworked lampe's example, and you can add a class using a selector in this way:
first apply the class to specific selectors in a javascript (repeat as many times you need for specific element selectors (in my HTML):
$("p:nth-of-type(even)").toggleClass("main mainswitch");
Then the html looks like this
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(".mainswitch").toggleClass("main");
});
});
</script>
<style>
.main {
font-size: 120%;
color: red;
}
</style>
</head>
<body>
<div>
<p>This is a paragraph.</p>
<p class="main mainswitch">This is another paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</div>
<button>Toggle class "main" for p elements</button>
</body>
</html>
If you're using Angular (cause it's not 2013 anymore), you can try the answer/solution/suggestion from here:
How can I change the targeted CSS file on a click event
It did the trick for me.
I have a document with a table and Print button. The print button calls a javascript function to generate a printable version in a new window. The printable version should load a stylesheet from the site. However the stylesheet does not load. And when I open the source from the newly opened window, although the stylesheet href -appears- correct, clicking on it does nothing. So clearly my browser doesn't recognise it as a proper href.
SO: Why is the link tag not being recognised as an href?
Here is the javascript function:
jQuery("div.jch-noise_records span.print_button a").on('click', function(e) {
e.preventDefault();
var getpanel = document.getElementById("jch-noise_records");
var MainWindow = window.open('', '', 'height=500,width=800');
MainWindow.document.write('<!DOCTYPE html>\r\n');
MainWindow.document.write( '<html lang="en-US">\r\n<head>\r\n');
MainWindow.document.write( '<title>Noise Records Report</title>\r\n');
MainWindow.document.write( '<link rel="stylesheet" href="http://example.com/wp-content/plugins/jchwebdev-noise_by_hour/jchwebdev-noise_by_hour.css" type="text/css" media="all" />\r\n');
MainWindow.document.write( '</head>\r\n');
MainWindow.document.write( '<body>\r\n');
MainWindow.document.write( getpanel.innerHTML);
MainWindow.document.write( '\r\n</body>\r\n</html>\r\n');
MainWindow.document.close();
MainWindow.document.focus();
// MainWindow.print();
return true;
});
And here is a bit of the html generated in the print window:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Noise Records Report</title>
<link rel='stylesheet' href='http://example.com/wp-content/plugins/jchwebdev-noise_by_hour/jchwebdev-noise_by_hour.css' type='text/css' media='all' />
</head>
<body>
<span class="close"><a title="Close" href="#">X</a></span><div class="jch_table_wrapper"><p class="header"><span class="report_date">2018-06-12 18:00</span><span class="report_title">Noise By The Hour (Checkbox Detail)</span><span class="report_ip">71.231.25.83</span></p><p class="header"><span class="report_query">For date >= 2018-01-01 AND date <= 2018-05-31</span></p><table id="jch-noise_by_hour" class="jch-noise"><tbody><tr class="total"><td colspan="5">Total of <span>151 </span> days tracked for <span></span> at <span> 12AM</span> from <span>01/01/2018</span> to <span>05/31/2018</span><br>
Average noise: <span>82.8dbA</span><br>
Total # of events detected: <span>12,153</span><br>
Average number of events/hour: <span>6</span></td></tr>
</tbody></table></div>
</body>
</html>
Although I'm guessing at why this is the issue, I wanted to put this answer here for visibility as it seems to have worked based on the comments on the question.
I believe the new popup window (or new tab depending on the user's settings) is not loading and rendering the linked CSS due to some sort of security/context issue.
Since the window.open(url, name, params); call you are making is passing in an empty string for the url and the name parameters I believe this is setting your new window to be in a different "protocol" or "domain" context than your opening page, AND the linked CSS file.
Someone like #EricLaw might be able to confirm this suspicion but I believe that "" (empty string), "about:blank", and "javascript:" trigger some special ~sandboxing~ when used for popups/iframes.
That all said, it appears that if you set the URL of your initial window.open() call to be an actual HTML page (it can be a dummy/stub) from your server... and then afterwards inject the CSS link you want and content to render in the body... it overcomes this issue.
I want to make these buttons which enable/disable the css across an entire website I am making. I am trying to make it so when a user clicks the button to disable/enable the css, it does so across all the webpages of the site and not just for the page a user is on.
So far, my code to enable/disable the css is as follows
<script>
$("#text-only").click(function () { jQuery('#mainStyleSheet').remove();});
$("#renable-style").click(function () {$('head').append('<link href="css/style.css" rel="stylesheet" id="mainStyleSheet" />');});
</script>
Any ideas?
{$('head').append('<link href="css/style.css" rel="stylesheet" id="mainStyleSheet" />');});
instead of
{$('head').html('<link href="css/style.css" rel="stylesheet" id="mainStyleSheet" />');});
in my opinion you should add a css class to every object that you have made in the webpage.In that class make all the changes.
I have a certain page that I want the user to be able to print using the native browser print page (window.print()) and I want to be able to show the user a preview of the page
I have a css file called print.css which looks like this :
#media print
{ ... }
The native print looks good but I can't figure out how to show the print preview, which means applying the css within "#media print" on demand
You could use jQuery to insert the css to the page on demand withouth the media print tag.
Instead of doing the media print you can do this in the HTML tag itself so you can use the css file for multiple purposes
Jquery:
$('head').append('<link rel="stylesheet" href="print.css" type="text/css" />');
Adding a media tag in the HTML:
<link rel="stylesheet" type="text/css" href="print.css" media="print">
Imagine a webpage which enables users to show an hidden element, using javascript to modify css a CSS style at runtime.
After his decision (which includes the modification of the stlyesheet) the user uses the printing functionality of his browser.
It seems that Internet Explorer does not respect the changes made in the stylesheet before during printing if the original css definition is located in an external file.
In other Browsers everything works as expected.
Please have a look at the example below, which changes a style class from its initial definition display:none to display:inline at runtime hence the element will be displayed.
But when printing this page, the element remains hidden in internet explorer (tested with IE 6,7,8).
Do you have a solution or workaround?
Minimalistic example (html file):
<html><head>
<LINK rel="stylesheet" type="text/css" href="minimal.css">
</head><body onload="displayCol();">
<script>
function displayCol()
{
var myrules;
if( document.styleSheets[0].cssRules ) {
myrules = document.styleSheets[0].cssRules;
} else {
if ( document.styleSheets[0].rules ) {
myrules = document.styleSheets[0].rules;
}
}
myrules[0].style.display = "inline";
}
</script>
<div class="col0" id="test">This is hidden by default.</div></body></html>
minimal.css
.col0 {
display:none;
}
UPDATE:
Please note that the decision if the object should be displayed or not is made by the user - it's not known at runtime!
Have you considered using the media=print way of getting the browser to use a stylesheet specifically for printing?
<link rel="stylesheet" href="print.css" media="print" />
If the css changes you are making are always the same, i.e. you can technically store them on a separate css file, then you can use this.
For non-static CSS, in IE (not sure about other browsers/later versions of IE), you could consider using the onbeforeprint event.
See here: http://www.javascriptkit.com/javatutors/ie5print.shtml
Instead of using javascript to change the stylesheet rules, use scripting to apply and remove classes to the elements that need to be displayed. Remember that an element can have more than one class applied to it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Demo</title>
<style type="text/css">
.col0 {display:none;}
div.showCol {display: inline;}
</style>
<script type="text/javascript">
function displayCol() {
document.getElementById("test").className += " showCol";
}
</script>
</head>
<body onload="displayCol();">
<div class="col0" id="test">This is hidden by default.</div>
</body>
</html>
This answer to another question does a great job laying out different ways to do this with scripting: Change an element's class with JavaScript
You could try using a specific style sheet for printing, for example:
<link rel="stylesheet" type="text/css" href="print.css" media="print" />
EDIT - too slow :)
Javascript is not being evaluated when printing. It will look just like when Javascript is turned off. You need an extra media=print stylesheet and make any necessary changes there.
If that is not an option, you could create a link that will generate a static page that will look like it's supposed to for that particular user.
Based off your example scenario - in your style sheet add:
.col0 {
display: none;
}
body.showColumn .col0 {
display: inline;
}
Then simply toggle the .showColumn class on your body, and the column's visibility will be toggled accordingly.