Grabbing style.display property via JS only works when set inline?
This is a "feature" of CSS. To actually get the style, you need to use window.getComputedStyle (most browsers) or element.currentStyle (Internet Explorer).
A fix to implement window.getComputedStyle IE can be found at: http://snipplr.com/view/13523/getcomputedstyle-for-ie/. Additionally, see this page for more info: http://www.quirksmode.org/dom/getstyles.html#link7 (there is a script near the bottom for a cross-browser getComputedStyle alternative).
This should work in all browsers (based on function from QuirksMode link above):
var elem = document.getElementById("myDiv");
if (elem.currentStyle) {
var displayStyle = elem.currentStyle.display;
} else if (window.getComputedStyle) {
var displayStyle = window.getComputedStyle(elem, null).getPropertyValue("display");
}
alert(displayStyle);
Inline styles causing problems when replacing an element
I managed to resolve this issue by using a string slice on the HTML element and patching the CSS elements to it. First I saved the current elements style properties using var currStyles = $alert.attr("style");
Afterwards I split the string of the updated element which is fed through the API and added the inline styles to it. I assigned this to a new variable called updatedBar:
var updatedBar = newBarHtml.slice(0,6) + ' style="' + currStyles + '"' + newBarHtml.slice(6);
And then I replaced that element on the page with the updatedBar variable.
$alert.replaceWith(updatedBar);
The script now keeps the inline styles consistent after it grabs the new element from the page so the jQuery hide() and show() work as intended now.
How to get the applied style from an element, excluding the default user agent styles
There is a read only property of document called 'styleSheets'.
var styleSheetList = document.styleSheets;
https://developer.mozilla.org/en-US/docs/Web/API/Document/styleSheets
By using this, you can reach all the styles which are applied by the author.
There is a similar question about this but not a duplicate, in here:
Is it possible to check if certain CSS properties are defined inside the style tag with Javascript?
You can get the applied style from an element, excluding the default user agent styles using the accepted answer of that question i just mentioned.
That answer didn't supply the element's own style
attribute content, so i have improved the code a bit:
var proto = Element.prototype;var slice = Function.call.bind(Array.prototype.slice);var matches = Function.call.bind(proto.matchesSelector || proto.mozMatchesSelector || proto.webkitMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector);
// Returns true if a DOM Element matches a cssRulevar elementMatchCSSRule = function(element, cssRule) { return matches(element, cssRule.selectorText);};
// Returns true if a property is defined in a cssRulevar propertyInCSSRule = function(prop, cssRule) { return prop in cssRule.style && cssRule.style[prop] !== "";};
// Here we get the cssRules across all the stylesheets in one arrayvar cssRules = slice(document.styleSheets).reduce(function(rules, styleSheet) { return rules.concat(slice(styleSheet.cssRules));}, []);
var getAppliedCss = function(elm) { // get only the css rules that matches that element var elementRules = cssRules.filter(elementMatchCSSRule.bind(null, elm)); var rules =[]; if(elementRules.length) { for(i = 0; i < elementRules.length; i++) { var e = elementRules[i]; rules.push({ order:i, text:e.cssText }) } } if(elm.getAttribute('style')) { rules.push({ order:elementRules.length, text:elm.getAttribute('style') }) } return rules;}
function showStyle(){var styleSheetList = document.styleSheets;// get a reference to an element, then...var div1 = document.getElementById("div1");
var rules = getAppliedCss(div1);
var str = '';for(i = 0; i < rules.length; i++) { var r = rules[i]; str += '<br/>Style Order: ' + r.order + ' | Style Text: ' + r.text; } document.getElementById("p1").innerHTML = str;
}
#div1 {float:left;width:100px;}
div {text-align:center;}
<div id="div1" style="font-size:14px;"> Lorem ipsum </div><br/><br/><a href="javascript:;" onclick="showStyle()"> Show me the style. </a> <p id="p1"><p>
Get CSS value mid-transition with native JavaScript
It is very easy to port the jQuery script from the linked thread into its vanilla JavaScript equivalent and below is a sample. The output is printed on the right side (output#op
element) once timer expires.
All that we are doing is the following:
- Attach two event handlers to the element which triggers the transition (sometimes the triggering element can be different from the one that has animation). In the other thread, the element that is triggering the transition and the one that is being transitioned is the same. Here, I have put it on two different elements just for a different demo.
- One event handler is for
mouseover
event and this creates a timer (usingsetTimeout
) which gets theopacity
andtop
value of the element that is being transitioned upon expiry of timer. - The other event handler is for
mouseleave
event to clear the timer when the user has hovered out before the specific point at which we need theopacity
andtop
value to be obtained. - Getting the
opacity
andtop
value of the element that is being transitioned can be obtained by using thewindow.getComputedStyle
method. - Unlike the demo in the other thread (which uses
setInterval
), here I have usedsetTimeout
. The difference is thatsetInterval
adds an interval and so the function is executed everyx
seconds whereas the function passed tosetTimeout
is executed only once afterx
seconds. You can use whichever fits your needs.
var wrap = document.querySelector('.wrapper'), el = document.querySelector('.with-transition'), op = document.querySelector('#op');var tmr;
wrap.addEventListener('mouseenter', function() { tmr = setTimeout(function() { op.innerHTML = 'Opacity: ' + window.getComputedStyle(el).opacity + ', Top: ' + window.getComputedStyle(el).top; }, 2500);});wrap.addEventListener('mouseleave', function() { clearTimeout(tmr);});
.wrapper { position: relative; height: 400px; width: 400px; background: yellowgreen;}.with-transition { position: absolute; top: 0px; left: 100px; width: 200px; height: 100px; background: yellow; opacity: 0; transition: all 5s linear;}.wrapper:hover .with-transition { top: 300px; opacity: 1;}output { position: absolute; top: 50px; right: 50px;}
<div class='wrapper'> <div class='with-transition'></div></div><output id='op'></output>
Change display style property of a div using Javascript
Something to note: ==
is for comparison, =
is for assignment. Also, there are no closing input tags. Here's the finished snippet:
function showMe() { var foo = document.getElementById('hidden-div');
if(foo.style.display == '' || foo.style.display == 'none'){ foo.style.display = 'block'; } else { foo.style.display = 'none'; }}
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title></head><body> <input type="button" id="btn-me" onclick="showMe()">+ clicking here should display the checkboxes</input><br>
<div id="hidden-div" style="display:none;">
<input type="checkbox" id="check-1"> Check 1 <br> <input type="checkbox" id="check-2"> Check 2 <br> <input type="checkbox" id="check-3"> Check 3
</div></body></html>
Related Topics
Google Map API Route Request Limit
Convert from English Digits to Arabic Ones in HTML Page
How to Detect Which CSS Grid Column and Row an Element Is in Using JavaScript
Why Do Arabic Characters Behave as Separate Characters When Styling Single Arabic Character
Bootstrap 3 Popover Arrow and Box Positioning
Background Image Resizing to Fit
Detecting Screen Resolution to Load Alternative CSS a Good Idea
How to Make Multiple Read More Buttons in Same Page Using One Jquery
Change the Color of a Text in Div Using Jquery Contains
Add Custom Buttons on Slick Carousel
Detecting Physical Screen Dimensions of Webkit Devices in JavaScript
Fixed Positioned Element Flicker in Ie Only, How to Solve
Trigger Same CSS Animation on Every Click
How to Horizontal Scroll When Scrolling Vertical
Variable in JavaScript Statement
How to Disable Caching of Static Assets Like .CSS and .Js in Jsf2