If I have:
#em {
opacity:0.5;
}
How do I get #em's opacity using javascript? :D
I've got troubles with the following (it returns nothing):
return document.getElementById("em").style.opacity;
var em = document.getElementById("em");
var temp = window.getComputedStyle(em).getPropertyValue("opacity");
Now, the variable temp will have the value of opacity of "em".
Setting a CSS value in a stylesheet is not the same as setting it through the style property. You need to look at the getComputedStyle method to obtain this (and also currentStyle for older IE).
document.getElementById("em").style.opacity;
it will work fine if you use inline style .eg.
<div id="em" style="width: 50px; height: 50px; opacity: 0.5;">
Related
Got another basic question that I couldn't seem to find the answer for online. I can change the CSS property of an element easily using javascript,
document.getElementById("ExampleID").style.height="30px";
however whenever I try printing a property to the console, with
console.log(document.getElementById("ExampleID").style.height);
it prints a blank line instead of the property. How can I print a style property value of the desired element? Thank you very much
You can use getComputedStyle
let elem = document.getElementById('test');
let ht = window.getComputedStyle(elem, null).getPropertyValue("height");
console.log(ht)
.test {
height: 300px;
width: 300px;
border: 1px solid red;
}
<div class="test" id="test">Test</div>
Make sure you are testing with an actual element that will be returned from your selection (see example below). Otherwise your code is fine.
const elem = document.getElementById('elemId');
elem.style.height = '30px';
console.log(elem.style.height);
<div id="elemId"></div>
document.getElementById("ExampleID").style.height="30px";
console.log(document.getElementById('ExampleID').clientHeight);
console.log(document.getElementById('ExampleID').offsetHeight);
<div id="ExampleID">
clientHeight includes padding.<br>
offsetHeight includes padding, scrollBar and borders.
</div>
clientHeight includes padding.
offsetHeight includes padding, scrollBar and borders.
You need to check HTML part in this case.
If you are setting from javascript then Your code is working fine.
In case Styles defined in CSS use window.getComputedStyle()
The window.getComputedStyle() method returns an object that reports the values of all CSS properties of an element after applying active stylesheets and resolving any basic computation those values may contain. Individual CSS property values are accessed through APIs provided by the object or by simply indexing with CSS property names.
Here is working snippet:
var divEle=document.getElementById("ExampleID");
console.log("Before:height::"+divEle.style.height);
console.log("Before:color::"+divEle.style.color);
var heightCss = window.getComputedStyle(divEle, null).getPropertyValue("height");
var colorCss = window.getComputedStyle(divEle, null).getPropertyValue("color");
console.log("Before:height from css::"+heightCss)
console.log("Before:color from css::"+colorCss)
function changeCss(){
divEle.style.height="30px";
divEle.style.color="blue";
console.log("After:height::"+divEle.style.height);
console.log("After:color::"+divEle.style.color);
}
.divClass {
height: 40px;
color: red;
width: 40px;
border: 2px solid black;
}
<div class="divClass" id="ExampleID">test</div><div><input type="button" onClick="changeCss();" value="Change Css"/></div>
When working with calc()ulated properties in CSS, is it possible to access their expanded (i.e., actually calculated) values through Javacsript?
For instance, consider the following CSS:
:root {
--ratio: calc(16 / 9);
--width: 100px;
--height: calc(var(--width) / var(--ratio));
}
And Javascript:
const computedStyle = window.getComputedStyle(document.documentElement);
console.info(computedStyle.getPropertyValue('--height'));
One would expect to see 56px being printed; instead, the string "calc(var(--width) / var(--ratio))" is returned.
Even if you try applying it to some CSS class property and reading from the class declaration instead, it won't work:
.rectangle {
height: var(--height);
}
Javascript:
const rectangleClassDeclaration = /* find it through document.styleSheets */
console.info(rectangleClassDeclaration.style.getPropertyValue('height'));
And the console shows "var(--height)".
So, is there a way to access the final, calculated value through Javascript?
One hack that I could think of is applying the value to some DOM element and them reading from it instead.
CSS:
.rectangle {
height: var(--height);
}
HTML:
<div class="rectangle"></div>
Javascript:
const rectangle = document.querySelector('.rectangle');
const computedStyle = window.getComputedStyle(rectangle);
console.info(computedStyle.getPropertyValue('height'));
And then you would see 56px as the result. But this is kinda hacky, so it would be good to find out some way of accessing the variable's computed value directly. It works, anyway.
See my CodePen with working code.
It was my understanding that [some elem].style.maginTop would return a string with the element's top margin.
Instead, I'm always getting a blank string. I want to use this with the body, but I also tried on a div, and that didn't work either.
console.log(document.body.style.marginTop); // logs ""
console.log(typeof(document.body.style.marginTop)); // logs "String"
var elem = document.getElementById("testDiv");
console.log(elem.style.marginTop); // logs ""
body {
margin-top:100px;
}
#testDiv {
margin-top:50px;
}
hi!
<div id="testDiv">test</div>
I'm not sure what I'm doing wrong... Does anybody have a non-jQuery solution to this?
The HTMLElement.style only returns inline styles:
The HTMLElement.style property returns a CSSStyleDeclaration object that represents the element's style attribute.
To access the styles from stylesheets use Window.getComputedStyle(element):
The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.
var elem = document.getElementById("testDiv");
var style = window.getComputedStyle(elem);
//output
document.body.innerHTML = style.marginTop;
body {
margin-top:100px;
}
#testDiv {
margin-top:50px;
}
hi!
<div id="testDiv">test</div>
You can use getComputedStyle and getPropertyValue to get top margin.
console.log(document.body.style.marginTop); // logs ""
console.log(typeof(document.body.style.marginTop)); // logs "String"
var elem = document.getElementById("testDiv");
//console.log(elem.style.marginTop); // logs ""
console.log(getComputedStyle(elem).getPropertyValue("margin-top"));
alert(getComputedStyle(elem).getPropertyValue("margin-top"));
body {
margin-top:100px;
}
#testDiv {
margin-top:50px;
}
hi!
<div id="testDiv">test</div>
Tested and working.
I don't know why, but I got it working by implicitly assigning the margin-top by JS first. I know why my answer works (it's been over 2 years so I better know why). By setting the values of div#test and body to 50px and
100px like this:
document.getElementById("testDiv").style.marginTop = '50px';
document.body.style.marginTop = '100px';
I'm actually setting the CSS property/value of the elements inline:
<body style='margin-top: 100px'>
<div id='testDiv' style='margin-top: 50px'>test</div>
</body>
Whenever the .style property is used, the CSS property/value that follows it is always inline. One important thing to remember about inline CSS styles is that they have a higher priority than the other 2 means of CSS Declaration: external stylesheets (ex. <link href="file.css"...) and inline stylesheet (ex. <style>...</style>). The only way to override an inline style is to use !important (unless of course the inline style has !important as well.)
So if the.style property is used to read a property/value of an element, it'll only return the inline style value if it actually exists which in OP's case it never did and in my case it did because I used .style to assign the property/values. While my solution is correct, the answers by Nicolo and Mr. Karlsson are better since you'll get the values from all CSS stylesheets.
document.getElementById("testDiv").style.marginTop = '50px';
document.body.style.marginTop = '100px';
console.log(document.getElementById("testDiv").style.marginTop);
console.log(document.body.style.marginTop);
body {
margin-top: 100px;
}
#testDiv {
margin-top: 50px;
}
hi!
<div id="testDiv">test</div>
Hm, I tried it as well with the same result as you did. A quick google search turned up Using JavaScript to read html / body tag margin-top which uses style.getPropertyValue() to return the information you're looking for.
instead of using core javascript, let you use js library jQuery. Then use this syntaxt to get its value.:
console.log($('body').css('margin-top'));
for pure javascript use this
var element = document.body,
style = window.getComputedStyle(element),
margin_top = style.getPropertyValue('margin-top');
console.log(margin_top);
http://jsfiddle.net/hAw53/726/
This question already has answers here:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
(26 answers)
Closed 3 years ago.
This is what my code looks like:
$('.mainSpan:before').css('background','url(_gfx/cmn/main_bg.png)');
This does not seem to work so I'm asking if it's even possible to add
background images to shadow elements with jQuery.
It's not possible to directly access pseudo-elements with Javascript as they're not part of the DOM. You can read their style using the optional second argument - which most, although not all, browsers in current use support - in .getComputedStyle() but you can't directly change their style.
However, you could change their style indirectly by adding in a new style element containing new rules. For example:
http://jsfiddle.net/sjFML/
The initial CSS assigns the :before pseudo-element with a green background, which is turned to black by inserting a new style element.
HTML:
<div id="theDiv"></div>
CSS:
#theDiv {
height: 100px;
background: red;
}
#theDiv:before {
content:' ';
display: block;
width: 50px;
height: 50px;
background: green;
}
Javascript:
var styleElem = document.head.appendChild(document.createElement("style"));
styleElem.innerHTML = "#theDiv:before {background: black;}";
There is also solution with CSS Variables (aka custom properties):
var style = document.querySelector('.foo').style;
style.setProperty('--background', 'url(http://placekitten.com/200/300)');
.foo::before {
background: var(--background);
content: '';
display: block;
width: 200px;
height: 300px;
}
<div class="foo"></div>
For browser support see Can I use and here is link to Ponyfill (same as Polyfill, but you need to call a function)
Ponyfill work with CSS in link and style CSS, but if you use code below, you can set the variable like with setProperty (it will run only in browsers that don't support CSS Variables like IE11)
var style = document.querySelector('.foo').style;
style.setProperty('--background', 'url(http://placekitten.com/200/300)');
cssVars({
variables: {'--background': 'url(http://placekitten.com/200/300)'}
});
.foo::before {
background: var(--background);
content: '';
display: block;
width: 200px;
height: 300px;
}
<div class="foo"></div>
<script src="https://unpkg.com/css-vars-ponyfill#2/dist/css-vars-ponyfill.min.js"></script>
Unfortunately the cssVar ponyfill is global like setting var on :root. If you need to support IE11 or other old browser you can try to search for better polyfill or library.
It is possible to change the value of the ::after element but not directly. Gotta be sneaky. Works on all browsers.
Let's say you have an element:
<div class="thing1">hi here</class>
And you got an ::after css style for it:
.thing1::after {
content:"I am what comes ::after a thing :)";
display: inline-block;
background-color: #4455ff;
padding:3px;
border: 1px solid #000000; }
And you want to change the content and the background color of the ::after pseudo-element using javascript. To do this, make a second CSS rule with the changes you want applied and have both the current class name and add a totally new class name to it. So let's say I want to change the content and the background color a bit and leave the rest of the stuff, the same:
.thing1.extra_stuff::after {
content:"Some parts of me, changed!";
background-color: #8888cc; }
Now, you can just fire off an onclick javascript event that will apply those two new rules to the element, by adding the second class name, to the element :) yay
function change_the_after_attribute(thing_button) {
thing_button.className="thing1 extra_stuff"; }
https://jsfiddle.net/bt8n26a5/
fun side notes:
You can use thing_button.classList.add("extra_stuff"); and thing_button.classList.remove("extra_stuff"); to make the function applicable to many different elements with many different class names, and to be able to remove your changes, as well!
Use a variable instead of the "extra_stuff" string to change what you're adding more dynamically.
how can I change image opacity using javascript? I'm going to create a fading effect using javascript, is there any sample? is there anything like image.opacity that can be changed through JS code? how is it set?
thanks
Supposing you're using plain JS (see other answers for jQuery), to change an element's opacity, write:
var element = document.getElementById('id');
element.style.opacity = "0.9";
element.style.filter = 'alpha(opacity=90)'; // IE fallback
You can use CSS to set the opacity, and than use javascript to apply the styles to a certain element in the DOM.
.opClass {
opacity:0.4;
filter:alpha(opacity=40); /* For IE8 and earlier */
}
Than use (for example) jQuery to change the style:
$('#element_id').addClass('opClass');
Or with plain javascript, like this:
document.getElementById("element_id").className = "opClass";
In fact, you need to use CSS.
document.getElementById("myDivId").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");
It works on FireFox, Chrome and IE.
You could use jQuery's animate or fadeTo.
I'm not sure if you can do this in every browser but you can set the css property of the specified img. Try to work with jQuery which allows you to make css changes much faster and efficiently. in jQuery you will have the options of using .animate(),.fadeTo(),.fadeIn(),.hide("slow"),.show("slow") for example. I mean this CSS snippet should do the work for you:
img
{
opacity:0.4;
filter:alpha(opacity=40); /* For IE8 and earlier */
}
Also check out this website where everything further is explained: http://www.w3schools.com/css/css_image_transparency.asp
You could use Jquery indeed or plain good old javascript:
var opacityPercent=30;
document.getElementById("id").style.cssText="opacity:0."+opacityPercent+"; filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity="+opacityPercent+");";
You put this in a function that you call on a setTimeout until the desired opacity is reached
First set the opacity explicitly in your HTML thus:
<div id="box" style="height:150px; width:150px; background-color:orange; margin:25px; opacity:1"></div>
otherwise it is 0 or null
this is then in my .js file
document.getElementById("fadeButton90").addEventListener("click", function(){
document.getElementById("box").style.opacity = document.getElementById("box").style.opacity*0.90; });