Disabling or hiding stylesheets, how do you do it? - javascript

I'm building a website that has to run entirely out of one window - it can never load another page. Consequently, I'm using a lot of JS to swap out the content that is displayed on the screen, and it's actually working rather well. However, I'm running out of good selectors and I don't want my stylesheet to get to be excessively long. So, I am wondering: is it possible to disable a stylesheet by placing it inside a div that is set to display:none?
For example:
<div style="display:none;">
<style type="text/css">
#my_image{
height:100px;
background-color:red;
}
</style>
</div>
<style type="text/css">
#my_image{
height:30px;
}
</style>
In this scenario, which of these would apply? I know that if both are loaded, the second one will be the latest one so it will be the one that is read. But let's say the div is not colored at all from the start. Would it be red when this script is run?
If this is not a viable solution to disable styles, then please inform me of what is.

You should ideally be using a separate stylesheet for each of your "themes".
You could then only load the correct stylesheet at runtime or:
Use javascript to create / destroy css link elements in the head
Use javascript to add a class to the body tag 'red' or 'blue' etc. Then have every selector in your theme begin with that class name:
.blue .header { background: red; }

Related

How to use the pseudo selectors in Inline Css in material UI? [duplicate]

I have a case where I must write inline CSS code, and I want to apply a hover style on an anchor.
How can I use a:hover in inline CSS inside the HTML style attribute?
E.g., you can't reliably use CSS classes in HTML emails.
Short answer: you can't.
Long answer: you shouldn't.
Give it a class name or an id and use stylesheets to apply the style.
:hover is a pseudo-selector and, for CSS, only has meaning within the style sheet. There isn't any inline-style equivalent (as it isn't defining the selection criteria).
Response to the OP's comments:
See Totally Pwn CSS with Javascript for a good script on adding CSS rules dynamically. Also see Change style sheet for some of the theory on the subject.
Also, don't forget, you can add links to external stylesheets if that's an option. For example,
<script type="text/javascript">
var link = document.createElement("link");
link.setAttribute("rel","stylesheet");
link.setAttribute("href","http://wherever.com/yourstylesheet.css");
var head = document.getElementsByTagName("head")[0];
head.appendChild(link);
</script>
Caution: the above assumes there is a head section.
You can get the same effect by changing your styles with JavaScript in the onMouseOver and onMouseOut parameters, although it's extremely inefficient if you need to change more than one element:
<a href="abc.html"
onMouseOver="this.style.color='#0F0'"
onMouseOut="this.style.color='#00F'" >Text</a>
Also, I can't remember for sure if this works in this context. You may have to switch it with document.getElementById('idForLink').
You could do it at some point in the past. But now (according to the latest revision of the same standard, which is Candidate Recommendation) you can't
.
You can't do exactly what you're describing, since a:hover is part of the selector, not the CSS rules. A stylesheet has two components:
selector {rules}
Inline styles only have rules; the selector is implicit to be the current element.
The selector is an expressive language that describes a set of criteria to match elements in an XML-like document.
However, you can get close, because a style set can technically go almost anywhere:
<html>
<style>
#uniqueid:hover {do:something;}
</style>
<a id="uniqueid">hello</a>
</html>
If you actually require inline code, this is possible to do. I needed it for some hover buttons, and the method is this:
.hover-item {
background-color: #FFF;
}
.hover-item:hover {
background-color: inherit;
}
<a style="background-color: red;">
<div class="hover-item">
Content
</div>
</a
In this case, the inline code: "background-color: red;" is the switch colour on hover. Use the colour you need and then this solution works. I realise this may not be the perfect solution in terms of compatibility, however this works if it is absolutely needed.
While it appears to be impossible to define a hover-rule inline, you can define the value of styles inline using a CSS variable:
:hover {
color: var(--hover-color);
}
<a style="--hover-color: green">
Library
</a>
Consider using an attribute or a class in addition to the selector (e.g., [hover-color]:hover) to allow coexistence with other low specificity hover color changing rules (from, e.g., a CSS reset or some elements using the default style).
Using JavaScript:
a) Adding inline style
document.head.insertAdjacentHTML('beforeend', '<style>#mydiv:hover{color:red;}</style>');
b) or a bit harder method - adding "mouseover"
document.getElementById("mydiv").onmouseover= function(e){this.className += ' my-special-class'; };
document.getElementById("mydiv").onmouseleave= function(e){this.className = this.className.replace('my-special-class',''); };
Note: multi-word styles (i.e.font-size) in JavaScript are written together:
element.style.fontSize="12px"
This is the best code example:
<a
style="color:blue;text-decoration: underline;background: white;"
href="http://aashwin.com/index.php/education/library/"
onmouseover="this.style.color='#0F0'"
onmouseout="this.style.color='#00F'">
Library
</a>
Moderator Suggestion: Keep your separation of concerns.
HTML
<a
style="color:blue;text-decoration: underline;background: white;"
href="http://aashwin.com/index.php/education/library/"
class="lib-link">
Library
</a>
JS
const libLink = document.getElementsByClassName("lib-link")[0];
// The array 0 assumes there is only one of these links,
// you would have to loop or use event delegation for multiples
// but we won't go into that here
libLink.onmouseover = function () {
this.style.color='#0F0'
}
libLink.onmouseout = function () {
this.style.color='#00F'
}
Inline pseudoclass declarations aren't supported in the current iteration of CSS (though, from what I understand, it may come in a future version).
For now, your best bet is probably to just define a style block directly above the link you want to style:
<style type="text/css">
.myLinkClass:hover {text-decoration:underline;}
</style>
Foo!
As pointed out, you cannot set arbitrary inline styles for hover, but you can change the style of the hover cursor in CSS using the following in the appropriate tag:
style="cursor: pointer;"
<style>a:hover { }</style>
Go Home
Hover is a pseudo class, and thus cannot be applied with a style attribute. It is part of the selector.
You can do this. But not in inline styles. You can use onmouseover and onmouseout events:
<div style="background: #333; padding: 10px; cursor: pointer"
onmouseover="this.style.backgroundColor='#555';" onmouseout="this.style.backgroundColor='#333';">
Hover on me!
</div>
According to your comments, you're sending a JavaScript file anyway. Do the rollover in JavaScript. jQuery's $.hover() method makes it easy, as does every other JavaScript wrapper. It's not too hard in straight JavaScript either.
There is no way to do this. Your options are to use a JavaScript or a CSS block.
Maybe there is some JavaScript library that will convert a proprietary style attribute to a style block. But then the code will not be standard-compliant.
You can write code in various type.
First I can write this
HTML
<a href="https://www.google.com/" onMouseOver="this.style.color='red'"
onMouseOut="this.style.color='blue'" class="one">Hello siraj</a>
CSS
.one {
text-decoration: none;
}
You can try another way:
HTML
Hello siraj
CSS
.one {
text-decoration: none;
}
.one:hover {
color: blue;
}
.one:active {
color: red;
}
You can also try hover in jQuery:
JavaScript
$(document).ready(function() {
$("p").hover(function() {
$(this).css("background-color", "yellow");
}, function() {
$(this).css("background-color", "pink");
});
});
HTML
<p>Hover the mouse pointer over this paragraph.</p>
In this code you have three functions in jQuery. First you ready a function which is the basic of a function of jQuery. Then secondly, you have a hover function in this function. When you hover a pointer to the text, the color will be changed and then next when you release the pointer to the text, it will be the different color, and this is the third function.
I just figured out a different solution.
My issue: I have an <a> tag around some slides/main content viewer as well as <a> tags in the footer. I want them to go to the same place in IE, so the whole paragraph would be underlined onHover, even though they're not links: the slide as a whole is a link. IE doesn't know the difference. I also have some actual links in my footer that do need the underline and color change onHover. I thought I would have to put styles inline with the footer tags to make the color change, but advice from above suggests that this is impossible.
Solution: I gave the footer links two different classes, and my problem was solved. I was able to have the onHover color change in one class, have the slides onHover have no color change/underline, and still able to have the external HREFS in the footer and the slides at the same time!
It's not exactly inline CSS, but it is inline.
<a href="abc.html" onMouseOver="this.style.color='#0F0'"
onMouseOut="this.style.color='#00F'">Text</a>
I agree with shadow. You could use the onmouseover and onmouseout event to change the CSS via JavaScript.
And don't say people need to have JavaScript activated. It's only a style issue, so it doesn't matter if there are some visitors without JavaScript ;)
Although most of Web 2.0 works with JavaScript. See Facebook for example (lots of JavaScript) or Myspace.
So this isn't quite what the user was looking for, but I found this question searching for an answer and came up with something sort of related. I had a bunch of repeating elements that needed a new color/hover for a tab within them. I use handlebars, which is key to my solution, but other templateing languages may also work.
I defined some colors and passed them into the handlebars template for each element. At the top of the template I defined a style tag, and put in my custom class and hover color.
<style type="text/css">
.{{chart.type}}-tab-hover:hover {
background-color: {{chart.chartPrimaryHighlight}} !important;
}
</style>
Then I used the style in the template:
<span class="financial-aid-details-header-text {{chart.type}}-tab-hover">
Payouts
</span>
You may not need the !important
While the "you shouldn't" context may apply there may be cases were you still want to achieve this. My use case was to dynamic set a hover color depending on some data value to achieve that with only CSS you can benefit from specificity.
Approach CSS only
CSS
/* Set your parent color for the inherit property */
.sidebar {
color: green;
}
/* Make sure your target element "inherit" parent color on :hover and default */
.list-item a {
color: inherit
}
.list-item a:hover {
color: inherit
}
/* Create a class to allows to get hover color from inline style */
.dynamic-hover-color:not(:hover) {
color: inherit !important;
}
Then your markup will be somewhat like:
Markup
<nav class="sidebar">
<ul>
<li class="list-item">
<a
href="/foo"
class="dynamic-hover-color"
style="color: #{{category.color}};"
>
Category
</a>
</li>
</ul>
</nav>
I'm doing this example using handlebars but the idea is that you take whatever is convenient for your use case to set the inline style (even if it is writing manually the color on hover you want)
You can just use an inline stylesheet statement like this:
<style>#T1:hover{color:red}</style><span id=T1>Your Text Here</span>
You can use the pseudo-class a:hover in external style sheets only. Therefore I recommend using an external style sheet. The code is:
a:hover {color:#FF00FF;} /* Mouse-over link */
You can do id by adding a class, but never inline.
<style>.hover_pointer{cursor:pointer;}</style>
<div class="hover_pointer" style="font:bold 12pt Verdana;">Hello World</div>
It is two lines, but you can reuse the class everywhere.
My problem was that I'm building a website which uses a lot of image-icons that have to be swapped by a different image on hover (e.g. blue-ish images turn red-ish on hover).
I produced the following solution for this:
.container div {
width: 100px;
height: 100px;
background-size: 100px 100px;
}
.container:hover .withoutHover {
display: none;
}
.container .withHover {
display: none;
}
.container:hover .withHover {
display: block;
}
<p>Hover the image to see it switch with the other. Note that I deliberately used inline CSS because I decided it was the easiest and clearest solution for my problem that uses more of these image pairs (with different URL's).
</p>
<div class=container>
<div class=withHover style="background-image: url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQrqRsWFJ3492s0t0NmPEcpTQYTqNnH188R606cLOHm8H2pUGlH')"></div>
<div class=withoutHover style="background-image: url('http://i.telegraph.co.uk/multimedia/archive/03523/Cat-Photo-Bombs-fa_3523609b.jpg')"></div>
</div>
I introduced a container containing the pair of images. The first is visible and the other is hidden (display:none). When hovering the container, the first becomes hidden (display:none) and the second shows up again (display:block).

Is it possible to create a Long Scroll Page (vertical) using only HTML and Javascript?

So I got this domain in a host site that allows only HTML and Javascript. The idea is to create a long scroll page, but the only way I find how to create it includes CSS. So I was hopeful that it can be done using only HTML and Javascript... Can it happen?
Hard to imagine a host site that doesn't allow CSS.
But, if that's the way you want to go, you can define all your CSS as inline styles inside your HTML, or, you can apply CSS through Javascript.
With regular javascript, it would look something like this
var blah= document.getElementById('whatever');
blah.style.background-color= "green";
With Jquery, it would look more like this
$('#whatever').css("background-color", "green");
You can do this for any CSS properties you want to add. Although, what Gavin Foster said is true, the overall height of your HTML document will adjust to fit the content so there is no additional CSS needed to make your page scroll up and down as long as there is content enough to fill up the page. The problem is, without CSS, you can't give anything a height, and therefore, you might end up with rather crowded-looking page and it might be hard to generate enough content to fill up the space you want to fill. The technique described above can solve this issue.
Alternately, you can define your CSS inside your HTML in 1 of 2 ways. You can either do something like this
<div style="background-color:blue;">This is a Blue Div</div>
Where you are simply adding all the CSS styles in the actual HTML tag for that element. This will make for an HTML document that has more clutter, and you won't be able to use and re-use classes.
Or, you can essentially put an entire CSS document in the head of your HTML document. Something like this:
<!DOCTYPE html>
<html lang="en"
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
body {
background-color: #00D1AC;
}
.whatever-class{
height: 500px;
width: 500px;
overflow: scroll;
}
</style>
</head>
<body>
... here, you put all the content of the body of the page
</body>
</html>
Where everything you would normally put inside a separate CSS document will instead be put inside of the <style> tag in your HTML head. This way, you can use classes as you normally would with CSS. This may be the easiest/laziest fix for your situation.

The right way to set an internal style or to manipulate the internal <style> sheet with JavaScript/jQuery

Let say I have this external "style.css" sheet:
p.class1 {
background-color: blue;
}
And my HTML content is this:
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<style>
p.class1 {
background-color: red;
}
p.class2 {
background-color: green;
}
</style>
</head>
<body>
<p class="class1">This is the first paragraph..</p>
<p class="class2">This is the second paragraph..</p>
</body>
For full source code example, visit this link! When I try this .css() code:
$('p.class1').css("background-color", "green");
It will set the p.class1's background-color inline, like:
<p class="class1" style="background-color: rgb(0, 255, 0);">
When I unset it with .css("background-color", ""), the inline style will be gone and the background will set back to red internally. What I want is to set the internal p.class1 style to "" or to remove it when I unset, so the background will become blue externally.. Is there a right way to manipulate the internal <style>?
Keep note, I don't want to remove the internal <style> element to perform the external p.class1 style if it will also affect the style for p.class2 or any attempt that will affect the style of the other in that element.
It is possible, but you will need to use CSSOM to manipulate the style sheet. This is not a jQuery thing, per se, though jQuery can help in the first stages.
The first step is getting to the internal <style> element in the DOM. The easiest way to do that would be to set an id attribute on it in your HTML and then use document.getElementById() to grab the element on the JavaScript side, but any method that can pick out that individual element will work. Assuming you use an id, the HTML might look like this:
<style id="internalStylesheet">
p.class1 {
background-color: red;
}
p.class2 {
background-color: green;
}
</style>
...and then in the JavaScript side...
var styleElem = document.getElementById('internalStylesheet');
Note that if you use jQuery to do this, you need the actual element, not the jQuery collection returned by jQuery().
Once you have the element, you can get into the CSSOM side through its .styleSheet property. Once you're in the stylesheet, the next step is to find the exact rule you want. CSS rules don't have unique IDs like DOM nodes can, so your only option is to search the list:
var desiredRule = null;
for (var i = 0; i < styleElem.styleSheet.cssRules.length; i += 1) {
if (styleElem.styleSheet.cssRules[i].selectorText === "p.class1") {
desiredRule = styleElem.styleSheet.cssRules[i];
break;
}
}
Keeping a reference to the rule you want is a good idea if you will have to change it many times. That way you won't have to repeat this search process every time you want to change the rule.
Once you have the rule you want, manipulating the rule is a lot like manipulating inline styles. For actually removing properties on the rule, I recommend something like this:
desiredRule.removeProperty("background-color");
Note that because of the inefficiences involved in searching the list, I don't recommend you do this unless the rule will affect many elements on the page, and it might have to be changed often. If that fits your use case, then it can be very fast, especially if you keep cached references to the rules you need to change. But this doesn't actually describe many common use cases, and when it doesn't, it's troublesome enough that it could be called premature optimization.
The only way to have a conflicting external CSS file override the inline <style> element without changing your HTML file at all, based on the code in your question, is by adding the !important hack to your external CSS file:
p.class1 {
background-color: blue !important;
}
But this is a hack, is bad, and should not be done, because you are throwing away the "Cascading" part of CSS when you use !important; instead, you should just remove p.class1 { background-color: red; from your inline <style> element, or replace its value with blue, since you don't want red to be used.
Instead, you should have your external stylesheet load after the <style> element. This can be done by simply flipping their order:
<head>
<style>
p.class1 {
background-color: red;
}
p.class2 {
background-color: green;
}
</style>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
This will override the <style>'s p.class1 value of red with the CSS file's p.class1 value of blue.
Alternatively, if you add a wrapper/container element around your <p> elements, you can set your external CSS file to have a more specific selector, which would override the less specific selector in the <style> element. Something like:
HTML:
<div class="wrapper">
<p class="class1">This is the first paragraph..</p>
<p class="class2">This is the second paragraph..</p>
</div>
CSS:
.wrapper p.class1 {
background-color: blue;
}
Since the selector .wrapper p.class1 is more specific than the inline selector p.class1, it will normally override the inline selector.
Firstly, there is no real difference between the external stylesheet and the internal <style> tag. The one defined later will take effect. I presume you have included your CSS before your <style>, so this part of the CSS will never work:
p.class1 {
background-color: blue;
}
Secondly, all inline styles will overwrite any CSS, so your jQuery .css() calls will always work. Setting it to an empty string will remove that inline style property, so it will naturally fall back to the lower-priority stylesheets - in your case,
<style>
p.class1 {
background-color: red;
}
...
</style>
Thirdly, no there is no way to manipulate the internal <style> dynamically. So if you want your p.class1 to revert to blue after inline styles are removed, you should either:
Declare your <link href="external.css"> after your <style>, which would then cancel out your p.class1 internal style. (This then begs the question of: why would you want to include that property for it to be cancelled out then?)
OR
Just use CSS and avoid internal styles.

Hide html only when Javascript is available

I guess this is more about SEO than wanting to support browsers with Javascript disabled. I have Javascript/jQuery code that reads in some html and basically displays it much nicer. The html is actually removed (with jQuery's .remove() function) during the process.
So I hide the html so there aren't any visual artifacts as the page loads. But now I want to only hide it if Javascript is enabled. I guess the easiest thing is to have some Javascript in <head> that adds the display: none css rule to the appropriate elements.
Is there a better way for dealing with this situation?
I think using noscript html tag will do the job. The tag displays the content inside if the script is disabled in users browser.
Any JavaScript will only work if JavaScript is enabled so no matter how you do it using JavaScript it will always work only if JavaScript is enabled so you never have to test for that.
That having been said, you can see how it is done in the HTML5 Boilerplate:
<html class="no-js" lang="en">
... the rest of the page
</html>
using a no-js class applied to the <html> tag. The class is later removed using JavaScript and a js class is added, both of which you can use in your CSS and HTML:
<p class="js">This is displayed if JavaScript is enabled</p>
<p class="no-js">This is displayed if JavaScript is disabled</p>
Or in CSS:
.no-js #someWidget { display: none; }
.js #someFallback { display: none; }
If you're using Modernizr then it will already change those classes for you, but even if you don't then all you have to do is something like:
document.documentElement.className =
document.documentElement.className.replace(/\bno-js\b/,'js');
It's a simple and elegant solution and all you have to worry about is CSS classes in your styles and markup.
I'd probably use a single bit of script that sets a class on body you can then reference in your CSS, but basically, you're on the right track.
E.g.:
<body>
<script>document.body.className = "jsenabled";</script>
Then your CSS rule:
body.jsenabled selector_for_your_initially_hidden_content {
display: none;
}
The rule will only kick in if the body has the class.
Complete example:
HTML (and inline script):
<body>
<script>document.body.className = "jsenabled";</script>
<div class='foo'>I'm foo, I'm hidden on load</div>
<div>I'm not foo, I'm not hidden on load</div>
<div class='foo'>Another foo</div>
<div>Another bit not hidden on load.</div>
</body>
CSS:
body.jsenabled div.foo {
display: none;
}
Live copy I've only used the "foo" class for an example. It could just as easily be a structural selector.
Add the class hiddenblock to each div (or block) you want to hide, and add this JS code in the header:
$(document).ready(function() {
$(body).addClass('jsenable');
$('.hiddenblock').hide();
}
You can also use the class jsenable to mask or modify some other block, like this:
.jsenable #myblock { position: absolute; right: 10000px; }

Is there any solution to disable Javascript style changes in print?

Is there any solution to disable Javascript style changes in print?
For instance, if I'm hiding something through Javascript but I want to include that hidden info in print.
I hid a div using Javascript and I want to show that div if Javascript is disabled. Now the problem is, because div is hidden using Javascript it's also not showing when the page is printed.
Use a print stylesheet, along with !important statements to force the element to be visible for printing.
<link rel="stylesheet" href="print.css" type="text/css" media="print" />
CSS:
#myDiv { display: block!important; }
I've found a workaround (at least, it works for me). In my instance i had a basic html page with some styling (screen.css & print.css) plus some javascript to progressively enhance the page with extra features, etc.
When it came time to print the page i realised that the js was affecting the layout (since i was doing some css styling via jquery).
What i ended up doing was this:
in "screen.css"
body {
background-color: #ccc; /* or whatever colour your designer chose; if it NEEDS to be white, simply change something else (e.g. background-image, font-size, etc.) */
}
in "print.css"
body {
background-color: #fff;
}
in "the-javascript-file.js"
$(document).ready(function()
{
if (isPrinting() == false)
{
init();
}
});
function isPrinting()
{
var isPrint = false;
/* I'm not 100% sure about the string literal check 'rgb(255, 255, 255)',
should do some testing here with other values || other attributes...
(font-size, color, line-height, other attributes that will have the
greatest difference / variation between "screen" and "print" styles)
*/
if ($('body').css('background-color') == 'rgb(255, 255, 255)')
{
isPrint = true;
}
return isPrint;
}
function init()
{
// All sorts of awesome goes here
}
And that was it! It worked!
Here's an overview of what's happening:
User loads page
Browser loads "screen.css"
Body background colour is set to "#ccc"
Browser loads "the-javascript-file.js"
JS checks background colour... it's "#ccc"...
JS does its thing
User hits print command
Browser loads "print.css"
Body background colour changes to "#fff"
Browser loads "the-javascript-file.js"
JS checks body background colour
JS realises background colour is "#fff"
JS does nothing :)
Hope this helps someone out there :)
The use of !important has already been mentioned, but it is a blunt instrument and things get very complicated once you start needing to override things which are already !important.
One of the great benefits of CSS is that it allows you to separate style from structure. Instead of using JS to manipulate the style of an element, use it to manipulate the structure. For example, by manipulating the className property.
Your screen media stylesheet can then hide the element, while leaving it visible for the print media stylesheet.
This has the additional benefit that you don't need to think about having to override these styles as they won't apply in the first place (for print).

Categories