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');
Related
<html>
<style type="text/css">
a {
display: none;
}
</style>
<body>
<p id="p"> a paragraph </p>
google
</body>
<script type="text/javascript">
var a = (document.getElementById('a')).style;
alert(a.display);
var p = (document.getElementById('p')).style;
alert(p.display);
p.display = 'none';
alert(p.display);
</script>
</html>
The first and the second alert display nothing other than a empty string, which I thought should be none and block.
However after the intensionally display setting, the third alert finally alert none.
But Why? How could I retrieve the display property correctly?
Thanks.
The .style.* properties map directly onto the style attribute, not to the applied style. For that you want getComputedStyle.
I'd give serious consideration to toggling .className and separating the presentation from the logic entirely.
You need the computed value of the display property for the element. You can get this as follows. Note that most browsers support window.getComputedStyle() whereas the nearest equivalent in IE is the element's currentStyle property:
var el = document.getElementById('a');
var styleObj;
if (typeof window.getComputedStyle != "undefined") {
styleObj = window.getComputedStyle(el, null);
} else if (el.currentStyle != "undefined") {
styleObj = el.currentStyle;
}
if (styleObj) {
alert(styleObj.display);
}
I'd recommend using a JavaScript library for getting computed style. For example, using jQuery you can retrieve computed style with the css() method...
$("#a").css("display");
The css() method is a cross-browser solution as it internally uses the style object and both the getComputedStyle method and the currentStyle object.
If you can use jQuery, there is a method called .is
To check if something isn't displayed, I'd do ... $('someSelector').is(':visible') ...
This would return false if display attribute is set to None.
I am loading the below function in a empty HTML document ::
setTimeout(function() {
(function test(){
var elem = document.createElement('div');
body = document.body;
body.appendChild(elem);
var
rule = "lalalalallalaallllllllllllllaaaaaaaaaaaaaaa" ,
mod = 'Alex-z',
style = ['','<style id="s', mod, '">', rule, '</style>'].join('');
console.log(style);
elem.innerHTML += style;
})();
}, 2500);
Now I have a question, no matter how big rule is, I never see any text in the browser, why ? Can somebody explain, a very similar snippet is used in a JS feature detection library, called modenizer, so I would really be interested in knowing why nothing is showing up in my browser?
Because <style></style> is by default hidden in the browser and it is set display:none if you inspect element. It's because you wouldn't want your declared styles being showed in the browsers right?
I really don't know what you're going to do, but if you want to see your styles generated on that JS then use :
div style {
display: block;
}
You don't see any text in the browser because your output is:
"
<style id="sAlex-z">lalalalallalaallllllllllllllaaaaaaaaaaaaaaa</style>"
is the soft hyphen symbol and will be converted into the HTML name, which is and the result is not visible (http://www.ascii.cl/htmlcodes.htm)
The rest is just a <style> element, used only to set CSS rules and by default browser set style { display: none; }, so it's not visible.
a very similar sinppet is used in a JS feature detection library
called Modernizr
Yes, Modernizr use this kind of snippets to detect some features, because in most cases needs to create an empty element and try to set the property we are trying to test. Eg:
tests['textshadow'] = function() {
return document.createElement('div').style.textShadow === '';
}
I'm currently making a google chrome extension and am using this javascript to change dynamically the background color of the hovered element:
var bindEvent = function(elem ,evt,cb) {
//see if the addEventListener function exists on the element
if ( elem.addEventListener ) {
elem.addEventListener(evt,cb,false);
//if addEventListener is not present, see if this is an IE browser
} else if ( elem.attachEvent ) {
//prefix the event type with "on"
elem.attachEvent('on' + evt, function(){
/* use call to simulate addEventListener
* This will make sure the callback gets the element for "this"
* and will ensure the function's first argument is the event object
*/
cb.call(event.srcElement,event);
});
}
};
bindEvent(document,'mouseover', function(event)
{ var target = event.target || event.srcElement;
/* getting target.style.background and inversing it */
});
bindEvent(document,'mouseout', function(event)
{ var target = event.target || event.srcElement;
/* getting target.style.background and inversing it */
});
and when used with static values, like target.style.background = #FFFFFF; when the cursor hover an element and target.style.background = #00000; when the cursor leave the element, it works perfectly. However, when I try to get the value of target.style.background or even target.style.backgroundColor, I always get rgb(255,255,255), no matter what the background color of the element is.
I know how to convert rgb to hexa and how to inverse it, but if I can't get the initial value of the background, it's useless.
So, my question is: why do var foo = target.style.backgroundColor; always return rgb(255, 255, 255) and how do I get the correct value?
Additional notes: the extension will be ported to other browsers later, so a cross-browser solution would be nice if it is possible.
In my experience, target.style is only populated with inline styling. To get style including css definitions just use the getComputedStyle method. For example
//instead of this
target.style.backgroundColor
//try this
getComputedStyle(target).backgroundColor
*Note that using the getComputedStyle method returns a read-only object, and target.style should still be used to set the background color.
You can't use .style to get settings that haven't been defined using .style or style="". Most browsers implement other ways for getting at current style calculations, these are a minefield of oddities however.
Internet explorer has .currentStyle, whereas the rest tend to implement .getComputedStyle. It would be a good idea to read up on these two subjects, to see their implementation — however, as I have said retrieving style settings is a much more complicated process than it first seems.
Even jQuery's css method only returns settings that have been specifically determined on that element i.e. no inheritance.
The following could be of use however:
http://upshots.org/javascript/jquery-get-currentstylecomputedstyle
The only reliable way I know of is to associate a CSS class or ID with a colour, then extract that from an anchor in a hidden element, or simply from empty anchor tag with the class applied. Otherwise it really is about knowing what that colour is and having it already stored as a value somewhere. My HTML would be the following for this solution:
<style>
a:hover,
a#yourChosenIdName {
background-color:#00FF00;
}
</style>
<!-- -->
<script>
var el = document.getElementById('yourChosenIdName'),
getStyle = el.currentStyle ? el.currentStyle : getComputedStyle(el),
hoverBackgroundColor = getStyle.backgroundColor;
//do something with background-color
</script>
My CSS rule looks like this:
#my-div{
display: none;
position: absolute;
left: -160px;
bottom: -150px;
}
I'm trying to get value of the left-property like this:
document.getElementById('my-div').style.left
document.getElementById('my-div').offsetLeft
The problem is that both return null. Where is the problem?
The problem is that someElement.style.left only work if you have inline style. Since you apply your styling through a stylesheet, you will not be able to fetch the value the way you expect.
You have a couple of other approaches you could take to get the value through JavaScript:
window.getComputedStyle:
It is possible to get the computed style of an element using window.getComputedStyle, the problem is that it has quite limited support (IE9+). If you still want to use it you could wrap it up in a function to make it a bit easier to get each property:
function getCssProperty(elmId, property){
var elem = document.getElementById(elmId);
return window.getComputedStyle(elem,null).getPropertyValue(property);
}
// You could now get your value like
var left = getCssProperty("my-div", "left");
Working example
jQuery (or some other library):
Another option would be to use a JavaScript library like jQuery (or whatever you prefer), which will provide you with a cross-browser solution to get the value.
With jQuery you could use the .css() method to read the CSS-property of the element.
$(function () {
var left = $("#my-div").css("left");
});
Working example
You should call this
document.getElementById('my-div').style.left
document.getElementById('my-div').offsetLeft
when document is loaded, if you call it earlier it will return null because element doesnt exists yet. So you can use jQuery to determine when all content is loaded.
$(function() {
//put your code here
});
The problem is that, since CSS is loaded separately from the JS, there's no official way to ensure that the style.left property will be accurate. The style.left property is a different, higher-priority style override.
You'll need to use the getComputedStyle function.
https://developer.mozilla.org/en-US/docs/DOM/window.getComputedStyle
Ex:
var div = document.getElementById('my-div');
var style = getComputedStyle(div);
var left = style.getPropertyValue("left");
Maybe you have to call your functions after document ready.
If you use jQuery you can find left value faster:
$(document).ready(function() {
var $left = $('#my-div').css('left');
console.log($left);
});
This question already has answers here:
Overriding !important style
(11 answers)
Closed 1 year ago.
I tried to inject a style using this code:
document.body.style.color='green!important';
Per the CSS cascade ref, by applying the !important rule I can trump origin and specificity.
I tried to inject this using Firefox Firebug into www.google.com however no luck.
How do I inject a foreground color with an !important rule?
Per the spec, if you want to set the priority, not just the value, you have to use setProperty, like so:
document.body.style.setProperty ("color", "green", "important");
element.style.cssText = 'color:green !important';
should work for you.
style.cssText is the only way to add !important.
<script>
document.body.style.cssText='color: red !important;'
</script>
all answers are great but they all assumed the value of the attribute is fixed,, what if not
take look at my solution
this.style.setProperty("color", $(this).css('color'), "important");
instead of hand writing the value, I got it using jquery $(this).css('attr')
I would like to pose that it may not be working not so much due to any error in code (excepting the space) but more because modifying the body tag isn't a specific enough element, class, or what have you to create the desired effect.
Like for instance the page text of a search result has a class of "st".
all search results are each encapsulated in an
<li>
tag.
So some code to such effect might look like this:
var arr = document.getElementsByClassName('st');
for(i=0; i<arr.length; i++){
arr[i].style.color="green";
}
Use only this:
document.body.style.color="green";
you can not have to use important in this way. Anyway as Fatal pointed out, this will not work, when there is directly important rule in css stylesheet, that you need to override.
In that way, you have to dynamicaly create stylesheet and ad it inside head:
function addNewStyle(newStyle) {
var styleElement = document.getElementById('styles_js');
if (!styleElement) {
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = 'styles_js';
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
styleElement.appendChild(document.createTextNode(newStyle));
}
Then you can update style just like that
addNewStyle('body {color:green !important;}')
i need to keep !important for the following code how to do
<script> var size = $(window).width();
if(size >="1900" && size <="2890"){
$(document).ready(function(){ $(".myMove").click(function(){ $(".hqnblogo").animate({ left:'-22% ', top: '67%', height:'7%', }); $(".hqnbnaturalslogo").animate({ left: '86%', top: '20px', height:'7%', }); }); }); } </script>?