Clear all Javascript-applied styles - javascript

Let's say we have this
var e = document.getElementById("someElement");
e.style.borderColor = "gold";
e.style.background = "yellow";
e.style.padding = "5px";
// more style modifications via javascript
There may have been other styles set inline or in an external CSS file.
Is there a method to clear all Javascript-applied styles? Like e.style.* = inherit or e.removeJavaScriptAppliedStyles().

Here you go:
<div>hi</div>
<div>hi</div>
<div>hi</div>
<div>hi</div>
<div id="click">click</div>
//
$("div").css("color", "red");
$("#click").click(function () {
$("*").removeAttr("style");
});
Keep in mind James Bruckner's warning that this kills all inline styles that were hardcoded into the original HTML. Since Javascript changes CSS by manipulating the style attribute, there's no real way to distinguish what was original, and what was set programmatically. (EDIT. See the comments below.)
http://jsfiddle.net/FASvA/

As an option you could store initial style attribute (e._originalStyle = e.style.cssText) in a private property and restore it when you'll need to drop all styles applied via javascript (e.style.cssText = e._originalStyle)

Related

Add a StyleSheet in JS and allow it to be toggled dynamically

I know how to use JS to add a stylesheet to an HTML document:
// given CSS as text, add a <style> to the document
function addStyle(css) {
var style = document.createElement("style");
style.type = "text/css";
style.appendChild(document.createTextNode(css));
document.head.appendChild(style);
}
How do I create a checkbox that can toggle this (and only this) stylesheet on and off?
This answer gives hints about how to manipulate stylesheets in JS, but there does not appear to be a way of locating a specific stylesheet without looping through document.styleSheets and matching against document.styleSheets[i].cssRules[j].cssText, which seems unwieldy.
Is there a better way to do this, ideally without jQuery, than a double loop?
(My particular use case is for a userscript (e.g. Greasemonkey), though I avoid GM_addStyle for portability. All this really means is that I don't have direct control over the HTML; I'm modifying other sites.)
In writing this question, I figured out the answer, though it still leaves open the question of how to manipulate preexisting stylesheets without too many loops.
Basically, while I can't use getElementById() or querySelector() to find a style element by its id attribute (because it's not in the body), I can save the object itself when I create it:
// given CSS as text, add a <style> to the document and return it
function addStyle(css) {
var style = document.createElement("style");
style.type = "text/css";
style.appendChild(document.createTextNode(css));
document.head.appendChild(style);
return style;
}
var toggler = addStyle(`
tr.informational { display:none; }
`);
// create and insert the toggling checkbox
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = true;
checkbox.onchange = function() { toggler.disabled = ! toggler.disabled };
var label = document.createElement("label"); // <label> allows clicking on text
label.appendChild(checkbox);
label.appendChild(document.createTextNode("Hide informational rows"));
document.getElementById("buttons").appendChild(label); // add to button panel
I had previously thought that Greasemonkey's security prevented accessing its objects after it finishes loading. This would have meant the checkbox.onchange() line wouldn't work. My original code was therefore quite ugly, finding toggler_index by looping over document.styleSheets[] to find my CSS and then constructing independent JS within JS by hard-coding that index:
checkbox.setAttribute("onchange", `
var toggler = document.styleSheets[${toggler_index}];
toggler.disabled = ! toggler.disabled;
`);
Thanks to StackOverflow for forcing me to question my assumptions when simplifying my question for posting here!

Cross-browser dynamic setting of a CSS property

I have a function that gets many pieces of data and sets a CSS property for a defined element.
Here is the code:
function setStyle(element,property,target){
element.style[property] = target;
}
var EL = document.getElementById("id");
setStyle(EL,"width","50px");
It works well in most browsers but not for IE6–IE9.
I've found document.defaultView.getComputedStyle and element.currentStyle[type], but these methods get style and I can't use them to set.
Is there any way to do that for old IEs?
i don't want to use jQuery or any other JS library, thanks.
The default way would be element.style.property = "value", like:
document.getElementById("id").style.width = "50px";
There's no reason why it shouldn't work. But, as an alternative, consider setting the css style in a class, and adding it to the element by the className property.. It is widely supported:
css:
.myClass { width: 50px; }
js:
document.getElementById("id").className = "myClass";
EDIT
Yet another way around, that works in IE8+ (If you don't really need anything lower) would be setting the actual style atribute to the DOM element, so you can get the property as a parameter:
http://jsfiddle.net/ppf5qcvo/
function setStyle(element,property,target){
element.setAttribute("style", property + ":" + target);
}
var el = document.getElementById("test");
setStyle(el, "color", "red");
Have you considered using jQuery? It handles all the cross browser issues for you. You could accomplish the same thing with the following statement:
$('#id').width('50px');

Customization of css attributes

I'm trying to customize the color attribute of this element this way:
<h2 style="float:left;font-family:'Open Sans',sans-serif;color:#fbfbfb;font-size:40px;position:relative;margin-top:-458px;margin-left:90px;" class="main-title">TEST</h2>
js code (included in the top of the html page)
(function(){
document.getElementsByClassName('main-title').color = 'black';
})();
Doing this wouldn't change the color. Including it at the bottom of the page involves the same issue. Also, I've tried to include a css file which contains(.main-title{color:black;}) instead of that js file, but it still the same. How to fix this, please?
Any brilliant idea ?
There should be
document.getElementsByClassName('main-title')[0].style.color = 'black';
Because getElementsByClassName returns a collection not a single element. And color is a key in style property.
You have Top-margin = -458px so that element will never appear. So may be you are not able to view that element itself.
You need to update the style property of the element
document.getElementsByClassName('main-title')[0].style.color = 'black';
You can also update all the elements with this classname with the following
var els = document.getElementsByClassName('main-title');
for (var i = 0; i < els.length; i++){
els[0].style.color = 'black'
}

Change text color with Javascript?

I want to change the color of a title when a button is clicked.
This is my code, but it's not working and I can't figure out why not...
var about;
function init() {
about = document.getElementById("about").innerHTML;
about.style.color = 'blue';
}
<div id="about">About Snakelane</div>
<input type="image" src="http://www.blakechris.com/snakelane/assets/about.png" onclick="init()" id="btn">
You set the style per element and not by its content:
function init() {
document.getElementById("about").style.color = 'blue';
}
With innerHTML you get/set the content of an element. So if you would want to modify your title, innerHTML would be the way to go.
In your case, however, you just want to modify a property of the element (change the color of the text inside it), so you address the style property of the element itself.
use ONLY
function init() {
about = document.getElementById("about");
about.style.color = 'blue';
}
.innerHTML() sets or gets the HTML syntax describing the element's descendants., All you need is an object here.
Demo
Try below code:
$(document).ready(function(){
$('#about').css({'background-color':'black'});
});
http://jsfiddle.net/jPCFC/
innerHTML is a string representing the contents of the element.
You want to modify the element itself. Drop the .innerHTML part.

Cannot figure out onMouseOver

I'm just messing around learning about JavaScript and I wanted to change the color of my background by resting my mouse over a link. Really I just want to learn about onMouseOver. I have:
Visit W3Schools
I tried applying this to radio buttons too that would change the bg color onclick, however If I wanted a preview of the color (by using onMouseOver) that part didn't work as it doesn't with the above.
Is the solution so obvious I'm overlooking it? Thanks for any help.
No, it's not obvious. JavaScript is not so easy to handle. And you have to learn the types and names of the objects you can use in JavaScript.
The object document does not have a element bgcolor
What you are trying is to change the CSS-style of the element body of the document
document.body.style.backgroundColor = 'lightgreen';
One could do it by using the document object model (DOM) which is what you tried, but you have to respect the case. the correct form of the document's attribute is bgColor not bgcolor (Capital letter C).
// bad style
document.bgColor = 'lightgreen';
But it is not advisable. Why?
document is a part of the Document Object Model (DOM) and therefore
mostly responsible for the data and the structure of the ... well
... document. The bgColor attribute of document maybe a relic of
the dark HTML medieval, the pre CSS times.
The document should contain the data, and not the representation (aka style) of the data. That what the style attribute of every DOM element is for.
You can overrule the bgColor of the document simply by giving the body a CSS style for background-color. The document still has the bgColor attribute and the value, but what you see is the value of the CSS style
onmouseover needs to be all lower-case onmouseover and it needs to equal a function (object.onmouseover=function(){//some code...} if in its own file and onmouseover="functionName()" if inline)
Here's an example: updated http://jsfiddle.net/TH2u3/1/
the following works:
<!DOCTYPE html>
<html>
<head>
<script>
var p = {
onload: function() {
var a = document.getElementsByTagName("a")[0];
a.onmouseover = function() {
document.body.style.backgroundColor = "blue";
};
a.onmouseout = function() {
document.body.style.backgroundColor = "green";
};
}
};
</script>
</head>
<body onload="p.onload()">
Visit W3Schools
</body>

Categories