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.
Related
I'm trying to design a webpage somewhat similar in appearance to Microsoft's. (https://www.microsoft.com)
This includes building a image slideshow, which is why I looked up W3 Schools and found this: https://www.w3schools.com/howto/howto_js_slideshow.asp This is a great example and when writing all of my code in one html document it works, however, as I try to link to an external stylesheet it doesn't work anymore. I could alternatively founder on the js link but I don't think so, as switching to the next picture works. I searched stackoverflow for it already and people suggested adding ?v3 (or sth. like that) to the link, clearing my cache and so on. - so far nothing worked for my. I tried this in Chrome and Firefox.
Here's how I link to my CSS: (it's in the head)
<style>
<link rel="stylesheet" type="text/css" href="new theme.css">
</style>
Here's the js link: (at the end of the body)
<script type="text/javascript" src="js/new script.js?v=3"></script>
Any ideas why this could be? Maybe some other tutorials for this?
I'll include pictures of the working html which's got everything stuffed in it and one of the html with external js and CSS.
Thank you very much!
external - not working
internal - working like a charm
THANKS EVERYONE! - Simple spelling mistake! Sorry to bother you!
This is invalid :
<style>
<link rel="stylesheet" type="text/css" href="new theme.css">
</style>
Between <style> and </style>, there must be CSS code. However link is not CSS code, that's an HTML tag. The correct syntax is just :
<link rel="stylesheet" type="text/css" href="new theme.css">
Then, "new theme.css" has a space in its name, so it will likely be encoded to "new%20theme.css" and you'll get a 404. Don't use spaces within file names.
Finally, open your console to see any errors, especially to check if the CSS file is being fetched successfully.
Don't use any spaces in the names of the files, try using new_theme.css and new_script.js
Reference your CSS like this at the top of your HTML - inbetween the <head> tags.
<link rel="stylesheet" href="new_theme.css">
Also always try either Camel Case - "newTheme.css" or use an underscore "new_theme.css" when naming your files!
That should fix your problem! :)
You should not include the inside the style tag.
It should be inside the tag.
Ex.
<head>
<link rel="stylesheet" type="text/css" href="new%20theme.css">
<head>
Also when you have file names with spaces in between, you need to encode the name.
Example
href="new theme.css"
becomes
href="new%20theme.css"
<link rel="stylesheet" type="text/css" href="newtheme.css">
or
<style type="text/css">
css code here
</style>
open your console to see if it could find your css file
I know from many sources that applying CSS after the page has loaded can cause "flashing" effect - means the page will re-render the CSS.
For example:
<head></head>
<body>
<link rel="stylesheet"... />
</body>
However, I can't find any source for applying CSS(not inline) with JS after the page is loaded and how it's reflected by the re-rendering it self.
For example:
HTML:
<head>
<link rel="stylesheet" href="style.css" type="text/css" media="all" />
</head>
<body>
<div id="divid" class="displaynone"></div>
<script>
function showit(){
document.getElementById("divid").className += " displayblock";}
window.onload = showit;
</script>
</body>
CSS:
.displaynone {display:none;}
.displayblock {display:block;}
Will the second example will be forced to re-render the css after the page is loaded? I want to understand the deeps of how the displayblock is actually apply to the div.
If you apply your <link rel="stylesheet"... /> after your DOM elements in your markup you can end up with "flickering" effects. This is caused because when the browser load the CSS file (a network request is made), the DOM is being already displayed in the ViewPort (which has not yet any style applied).
In the second case where you add <link rel="stylesheet"... /> in your head, the browser download your CSS file before rendering the DOM on the ViewPort. At this point your JavaScript change class attribute to the DOM and you have no flickering (as all CSS has been already loaded).
When you change the DOM with a property which is related to the its visual representation the browser execute a "paint" this means that an area of the ViewPort is partially or fully re-rendered.
An interesting article regarding browser painting and performance and rendering path. Also of interest if you are using Chrome Dev Tools.
I've used the <noscript> tag to hide certain elements when javascript is not enabled; however, it doesn't seem to work.
My document declaration:
<!DOCTYPE html>
At the end of my file I typed the following:
<noscript>
<style type="text/css" scoped> #status {display:none;} </style>
</noscript>
</body>
</html>
But the #status div is still present even after disabling JS. Am I missing something here?
Remove the scoped attribute of the style tag. It's making your CSS apply strictly to the <noscript> tag.
If this attribute is present, then style applies only to its parent element.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style#Attributes
A simpler to manage solution would be to make the element hidden by default and use this :
<script>document.getElementById('status').style.display='block';</script>
(or an equivalent class based solution)
Try removing the scope of the style, like the code below.
<noscript>
<style type="text/css"> #status {display:none;} </style>
</noscript>
#dystroy's answer is the right way of doing it, because:
<style> elements can't be placed on <body> (except if they have scoped attribute)
<noscript> elements can't be placed on head.
But if you don't want a delay, you can use the following in <head>:
<style id="noScriptSheet" type="text/css">
.onlyScript{ display:none;}
</style>
<script type="text/javascript">
function kill(el){
return el.parentNode.removeChild(el);
}
kill(document.getElementById('noScriptSheet'));
</script>
And add a class to your element:
<div class="onlyScript">Hello world!</div>
Demo: http://jsfiddle.net/TQLfu/
I am adding this answer because this seems to be the most popular SO-question regarding the noscript tag.
It doesn't seem to fire at all with "Sybu JavaScript Blocker". So in case you are testing with that JavaScript blocker try using another JavaScript blocker. When I used "Toggle Javascript" the noscript tag fired without problem. I did not yet discover a way to detect that "Sybu JavaScript Blocker" is being used.
My Testing environment:
Sybu JavaScript Blocker, Version 2.93
Toggle JavaScript, Version 1.3
Chrome, Version 85.0.4183.83
I'm debugging a site on an Android HTC Sense. The site uses a lot of inserted content, which comes along with it's own CSS and JS like:
// wrapper id = snippet_id
<html>
<head>
<style type="text/css">
#snippet_id div {border: 1px solid red !important;}
div {border: 1px solid blue !important;}
</style>
</head>
<body>
<div>Hello World</div>
</body>
<html>
This is inserted into an existing page, so it sort these snippets are sort of like iFrames I guess.
Question:
Problem is, that while Javascript works fine, all CSS I'm specifying using <style> tags is being ignored. Any idea why?
EDIT:
Works on:
- Android 4.0.1
Does not work on:
- Android 2.3.1
- IOS 4.1
If I add the CSS to the main.css file being requested when the page loads, all is ok. If it's inside my gadget, it's not working.
EDIT:
So from what I can see, <style> does not seem to work on classes and id. If I use regular HTML elements as selectors it works.
EDIT:
My dev-site is here. I'm using a plugin called renderJs, which encapsultes HTML snippets (along with their CSS and JS) into resuable gadgets. Gadgets content will be appended to the page body, so although a gadget can act as a standalone HTML page, it can also be part of a page.
Example code from my page (I stripped out all gadgets but one below):
index.html - include index_wrapper gadget
<!DOCTYPE html>
<html itemscope itemtype="http://schema.org/Organization" lang="en" class="render">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/overrides.css">
<script data-main="../js/main.js" type="text/javascript" src="../js/libs/require/require.js"></script>
<title></title>
</head>
<body class="splash">
<div data-role="page" id="index">
<div id="index_wrapper" data-gadget="../gadgets/index_wrapper.html"></div>
</div>
</body>
</html>
The page has a gadget called index_wrapper link - code below:
<!DOCTYPE html>
<head></head>
<body>
<div id="index_social" data-gadget="../gadgets/social.html"></div>
<p class="mini t" data-i18n="gen.disclaimer"></p>
</body>
</html>
Which has another gadget called social here. This gadget includes some CSS, but on the devices in question, it is ignored (just saw, I'm missing a </div> in the index_wrapper, so trying to see if that fixed the problem, too).
The code below includes my fix:
<!DOCTYPE html>
<head>
<style type="text/css" scoped>
// will be ignroed
.el {width: 1px;}
.menu_social {text-align: center; margin: 1em 0;}
.action_menu {display: inline-block;}
.follow_us {display: inline-block; margin: 0; padding: 0 .5em 0 0;}
...
</head>
<body>
<div class="menu_social">
<div>
<span class="el ui-hidden-accessible"></span><!-- fallback for CSS not working -->
<div data-role="controlgroup" data-type="horizontal" data-theme="c" class="action_menu">
</div>
</div>
</div>
<script type="text/javascript">
//<![CDATA[
(function () {
$(document).ready(function() {
var gadget = RenderJs.getSelfGadget();
// fallback for old devices which cannot load <style> css
if (gadget.dom.find(".el").css('width') !== "1px") {
require(['text!../css/social.css'], function (t) {
var x = '<style>'+t+'</style>';
gadget.dom.append(x);
});
}
// trigger enhancement
$(this).trigger("render_enhance", {gadget: gadget.dom});
});
})();
//]]>
</script>
</body>
</html>
So aside from probably missing a closing </div> I'm still wondering why my embedded CSS is not working.
Looking at the generated HTML code (i.e., code as modified by JavaScript) of the demo page suggests that style elements are generated inside body. Although such elements are allowed by HTML5 drafts when the scoped attribute is present, support to that attribute seems to be nonexistent, and the style sheet is applied globally. It is possible however that some browsers do not apply it at all, at least when the style element is dynamically generated.
A better approach is to make all style sheets global to the document, preferably as external style sheets, and use contextual selectors to limit the rules to some elements only. And possibly using JavaScript to change classes of elements, rather than manipulating style sheets directly.
Ok. Ugly workaround:
In the inline section, set this:
<style>
.el {width: 1px;}
</style>
In the page, set hide an element el like this:
// ui-hidden-accessible is a JQM class, moving the item out of view
// since it uses pos:absolute, is needed to not break
// selects on the page (compare to JQM ui-icon)
<span class="el ui-hidden-accessible"> </span>
Then check for the width when running inline Javascript (which works) and require the inline CSS as a separate file, when the width is not at 1px
// fallback for old devices which cannot load <style> css
// gadget is my iframe-look-a-like
if (gadget.dom.find(".el").css('width') !== "1px") {
require(['text!../css/translate.css'], function (t) {
var x = '<style>'+t+'</style>';
gadget.dom.append(x);
});
}
Ugly and an extra HTTP request, but at least the CSS is working then.
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.