Javascript destroys CSS hover - javascript

I got a problem :/
I got a CSS thingy thast makes the background position change on hover. But after i run a function in javascript that changes the hover the CSS one stops working.
This is the function:
function tree() {
var boxfb = document.getElementById('fb_box');
var boxtw = document.getElementById('twitter_box');
var boxsun = document.getElementById('sun_box');
var boxtree = document.getElementById('tree_box');
var btn = document.getElementById('hbtr');
if(boxtree.style.visibility == "hidden") {
boxtw.style.visibility="hidden";
boxfb.style.visibility="hidden";
boxsun.style.visibility="hidden";
boxtree.style.visibility="visible";
btn.style.backgroundPosition="-150px -100px";
}
else {
boxtree.style.visibility="hidden";
btn.style.backgroundPosition="-150px 0";
}
}
Live at http://enji.se (Press the tree in the top left corner)

Because you're adding a 'style' attribute to your element, anything within this 'style' attribute will override any of your predefined CSS settings (it takes priority).
I this case, "btn.style.backgroundPosition="-150px 0";" is overriding your hover style of "-150px -100px", by adding it directly to the element.
I'm not sure exactly what you're going for here, and there's probably a more simplistic way to do what you're doing -- but I suppose that's not why you're here...
So to fix your problem I would suggest one of two things:
1) Add/Remove a class using javascript instead of a style attribute
-OR, as a quick fix-
2) add '!important' to Line 343 of your stylesheet, like so:
.tree:hover {
background-position: -150px -100px !important;
}

Related

Setting div height to equal width ( javascript )

I'm aware this is a popular question. I've read solutions to this including setting padding-bottom to equal width. As well as assigning this to the pseudo element so it's easier to insert content. (Plus other css solutions).
css height same as width
These do work but it's giving me trouble with some of the content I insert and it's not worth the hassle (since my whole site is construction from these squares).
I'm a novice when it comes to javascript but would there be an easy solution to enable a divs height to equal width. ( Sorry I'm too novice to even show an attempt :/ )
I try not to ask too many "write code for me" questions so references or explanations would be equally appreciated.
Answer: Thanks Jacob just to add onto your code this now works on resize incase anyone else has this same problem https://jsfiddle.net/pekqh5z1/4/
function updateSize(){
var box = $(".test");
box.css("height", box.width());
}
$( window ).resize(updateSize);
$(document).ready(function(){
updateSize();
})
This is super easy to do.
To edit set the style of an element with JS, you set the desired property of the style method.
var test = document.querySelector(".test");
test.style.height = getComputedStyle(test).width;
.test {
background: red;
}
<div class="test">Super uber goober</div>
With the JS, we first select the first appearance of .test, and assign it to a variable(var test = document.querySelector(".test");)
We then get the computed width of the element, and set that as its height(test.style.height = getComputedStyle(test).width;)
For the sake of completeness, here's a jQuery solution as well:
var test = $(".test");
test.css("height", test.width());
.test {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="test">Super uber goober</div>

jQuery overflow-y update to scroll briefly shows but then reverts to no-scroll

I find that when I update a div's overflow-y property to scroll the change happens only for a moment (I can just barely see the scroll var flicker in and out), and then the div reverts to its original overflow-y: hidden status.
Here's the code. First, I create a bunch of div elements like so:
$('#toAppend').append("<div id = '"+divName+"' class = 'unselected' style = 'overflow-x:hidden; overflow-y:hidden; float:left;'></div>");
Later on, when a div is clicked, I want to expand it and add a scroll bar so I use the following in click():
div.css("overflow-y", "scroll");
When I then click on a div, I very fleetingly see the scroll bar and then it disappears. There is no other css or jQuery touching this overflow-y property. Why doesn't the change remain?
Working example here.
Here's what I've tried to trouble-shoot:
I already have CSS classes that correspond to the selected and unselected states that regulate scrolling, so I tried adjusting overflow-y to scroll vs hidden. This also did not show any results.
Even though jQuery can use overflow-y I also tried calling css("overflowY"... using camel case. This also made no difference.
There aren't any error messages in the browser, and all other related updates for click events are happening.
Here is a larger code sample covering most of what is done:
$(document).ready(function(){
// set up sizing variables
width = $('#toAppend').width()*.9;
height = $('#toAppend').height()*.9;
widthPer = width/pageArray.length;
heightPer = height*.2;
// generate 1 div for each element in pageArray
for(i = 1; i <= pageArray.length; i++){
var divName = "div_"+i
$('#toAppend').append("<div id = '"+divName+"' class = 'unselected' style = 'overflow-x:hidden; overflow-y:hidden; float:left;'></div>");
$("#"+divName).load(pageArray[i-1]).css("width", Math.round(widthPer*PORTION_DIV)).css("height", heightPer).css("background-color", COLORS[i-1])
.css('cursor', 'pointer').css("border-radius", BORDER_RADIUS)
// expand div user clicks on and collapse other sections
.click(function(event){
var div = "#div_"+event.currentTarget.id.slice(-1);
if($(div).hasClass("unselected") || $(div).hasClass("almostSelected")){
var shrinkString = ""
var widthPerSmall = Math.round((1-MULTIPLE_TO)*width/(pageArray.length - 1));
var divToShrink = "";
// generate string of all divs other than selected one to shrink them down simultaneously
for(ii = 1; ii <= pageArray.length; ii++){
if(ii !== Number(event.currentTarget.id.slice(-1))){
var divShrink = "#div_"+ii;
shrinkString = shrinkString + divShrink +", " ;
if($(divShrink).hasClass("selected")){
divToShrink = divShrink;
$(divToShrink).switchClass("selected", "unselected", SHORT_TIME)
}
}
}
// shrink elements in a given order with nested callbacks
shrinkString = shrinkString.slice(0, -2);
$(shrinkString)
.animate({ width: widthPerSmall, height: heightPer}, LONG_TIME, function(){
$(div).animate({width: Math.round(MULTIPLE_TO*width), height: height}, LONG_TIME, function(){
if(divToShrink.length > 1){
toShrink = divToShrink.slice(-1)
$(divToShrink).load(pageArray[toShrink-1])
.css("background-color", COLORS[toShrink-1])
}
})
.switchClass(["unselected", "almostSelected"], "selected", LONG_TIME)
.load(longPageArray[Number(event.currentTarget.id.slice(-1))-1 ]).attr("class", "selected")
.css("background-color", "white").css("border", BORDER+COLORS[Number(event.currentTarget.id.slice(-1))-1])
.css("overflow-y", "scroll");
})
// this should be called only for first click, when no elements are yet selected
if(divToShrink.length < 1) $(div).animate({width: Math.round(MULTIPLE_TO*width), height: height}, LONG_TIME).switchClass(["unselected", "almostSelected"], "selected", LONG_TIME).load(longPageArray[Number(event.curren\
tTarget.id.slice(-1))-1 ]).attr("class", "selected").css("background-color", "white").css("border", BORDER+COLORS[Number(event.currentTarget.id.slice(-1))-1]).css("overflow-y", "scroll");
}
})
}
You need to apply your css in the callback of your animate function for expanding divs, instead of chaining it after animate() is called like you are currently doing. Chaining jQuery animation methods adds those functions to the fx queue, but non-animated methods like css() do not get added to that queue. Instead they are fired immediately. Taking a peek at the jQuery source you can see that when animating elements, jQuery changes the overflow to hidden and then changes it back to what it thinks the original overflow properties are when it is done with the animation. In this case, because of the async chain, jQuery goes with its original inline style instead of the one set in chained css() method. As a rule of thumb, if you are calling any jQuery method that is not an animation, don't chain it but put it in the callback.
The relevant block of code needs to be changed to this:
$(div).animate({width: Math.round(MULTIPLE_TO*width),height: height},
LONG_TIME,
function(){
if(divToShrink.length > 1){
toShrink = divToShrink.slice(-1)
$(divToShrink).load(pageArray[toShrink-1])
.css("background-color", COLORS[toShrink-1])
}
//APPLY THIS IN CALLBACK
$(this).css("overflow-y", "scroll");
})
Working fiddle
While jQuery will change the overflow to hidden for the animation, as you found out originally, by chaining that method you actually can override that for the duration of the animation. So if that is important to you, you can continue chaining the method and add it to the callback. It looks like in your particular instance, there is a conflict with the other animation method that would cause the overflow to revert to hidden for its duration, so the overflow will flicker. So that's up to you whether you include both or just keep the one call in the callback of animated methods.
Also as a side note, I noticed that you always chain your jquery css() functions on the same elements. You know you can save all properties as an object and just pass that in as a parameter to save yourself all of those function calls?

change css on scroll event w/ requestAnimation Frame

I want to change the background color of in-viewport elements (using overflow: scroll)
So here was my first attempt:
http://jsfiddle.net/2YeZG/
As you see, there is a brief flicker of the previous color before the new color is painted. Others have had similar problems.
Following the HTML5 rocks instructions, I tried to introduce requestAnimationFrame to fix this problem to no avail:
http://jsfiddle.net/RETbF/
What am I doing wrong here?
Here is a simpler example showing the same problem: http://jsfiddle.net/HJ9ng/
Filed bug with Chromium here: http://code.google.com/p/chromium/issues/detail?id=151880
if it is only the background color, well why don't you just change the parent background color to red and once it scroll just change it to pink?
I change your CSS to that
#dad
{
overflow-y: scroll;
overflow-x: hidden;
width: 100px;
height: 600px;
background-color:red;
}​
I remove some of you Jquery and change it to this
dad.bind('scroll', function() {
dad.css('background-color', 'pink');
});
And I remove this line
iChild.css('backgroundColor', 'red');
But is the Red color it is important that won't work for sure http://jsfiddle.net/2YeZG/5/
I like Manuel's Solution.
But even though I don't get what you're exactly trying to do, I want to point out a few things.
In your fiddle code, I saw that you included Paul Irish's Shim for requestAnimationFrame.
But you never use it.
(It's basically a reliable setTimeOut, nothing else) it's from frame based animations.)
So since you just want to change some CSS properties, I don't see why you would need it. Even if you want transitions, you should rely on CSS transitions.
Other than that your code could look something like
dad.bind('scroll', function() {
dad.css('background-color', 'pink');
eachElemNameHere.css('background-color','randomColor');
});
Also you should ideally not use something like that if you can help it. You should just add and remove class names and add all these properties in your CSS. Makes it work faster.
Also, again I don't quite get it, but you could use the jQuery function to find out each elements' position from the top to have better control.
Your problem seems to be that you only change the background color of the elements which have already been scrolled into view. Your code expects that the browser waits for your code to handle the scroll event before the browser redraws its view. This is most probably not a guarantee given by the HTML spec. That's why it flickers.
What you should do instead is to change the elements which are going to be scrolled into view. This is related to off screen rendering or double buffering as it is called in computer games programming. You build your scene off screen and copy the finished scene to the visible frame buffer.
I modified your first JSFiddle to include a multiplier for the height of the scroll area: http://jsfiddle.net/2YeZG/13/.
dad.bind('scroll', function() {
// new: query multiplier from input field (for demonstration only) and print message
var multiplier = +($("#multiplier")[0].value);
$("#message")[0].innerHTML=(multiplier*100)-100 + "% of screen rendering";
// your original code
var newScrollY = newScrollY = dad.scrollTop();
var isForward = newScrollY > oldScrollY;
var minVal = bSearch(bots, newScrollY, true);
// new: expand covered height by the given multiplier
// multiplier = 1 is similar to your code
// multiplier = 2 would be complete off screen rendering
var newScrollYHt = newScrollY + multiplier * dadHeight;
// your original code (continued)
var maxVal;
for (maxVal = minVal; maxVal < botsLen; maxVal++) {
var nxtTopSide = tops[maxVal];
if (nxtTopSide >= newScrollYHt) {
break;
}
}
maxVal = Math.min(maxVal, botsLen);
$(dadKids.slice(minVal, maxVal)).css('background', 'pink');
});
Your code had a multiplier of 1, meaning that you update the elements which are currently visible (100% of scroll area height). If you set the multiplier to 2, you get complete off screen updates for all your elements. The browser updates enough elements to the new background color so that even a 100% scroll would show updated elements. Since the browser seldom scrolls 100% of the area in one step (depends of the operating system and the scroll method!), it may be sufficient to reduce the multiplier to e.g. 1.5 (meaning 50% off screen rendering). On my machine (Google Chrome, Mac OS X with touch pad) I cannot produce any flicker if the multiplier is 1.7 or above.
BTW: If you do something more complicated than just changing the background color, you should not do it again and again. Instead you should check whether the element has already been updated and perform the change only afterwards.

Get real width of elements with jQuery

I am writing a validator for "visual correctness" of html files. The goal is to detect too wide elements.
Here is a demo of my problem.
The dotted red line is an indicator of the max width of the document (200px in this example). The first paragraph is fine, but the second is too wide. Nevertheless, all of the following commands still return "200px" as the width:
// all return 200, but the value should be larger
$('#two').width();
$('#two').outerWidth();
$('#two').prop('clientWidth');
Please see the Fiddle for more details.
How can i detect such oversized elements?
Updated question: Better to ask, how can i detect text that exceeds the borders of their parent elements?
Updated requirement: I am not allowed to change anything in the source HTML or CSS. But i can do anything i want with jQuery to modify the document, so that i can detect those too wide elements.
As others have said, temporarily wrap the text node in an inline element.
var two = document.getElementById('two'),
text = two.firstChild,
wrapper = document.createElement('span');
// wrap it up
wrapper.appendChild(text);
two.appendChild(wrapper);
// better than bad, it's good.
console.log(wrapper.offsetWidth);
// put it back the way it was.
two.removeChild(wrapper);
two.appendChild(text);
http://jsfiddle.net/vv68y/12/
Here is a getInnerWidth function that should be useful to you. Pass it an element and it will handle the wrapping and unwrapping.
function getInnerWidth(element) {
var wrapper = document.createElement('span'),
result;
while (element.firstChild) {
wrapper.appendChild(element.firstChild);
}
element.appendChild(wrapper);
result = wrapper.offsetWidth;
element.removeChild(wrapper);
while (wrapper.firstChild) {
element.appendChild(wrapper.firstChild);
}
return result;
}
http://jsfiddle.net/vv68y/13/
scrollWidth will do it:
$("#two").get()[0].scrollWidth
or
getElementById("two").scrollWidth
this outputs 212px, the real width you are looking for.
This effect is called "shrinkwrapping", and there's a couple of ways to determine the "real" width of the element.
Float
One of the ways that you can use is to float your <p> element which will force it as small as possible, but you'll need to use a clearfix if anything inside your div is floating:
#two { float: left; }
Inline-block element
Inserting an inline element should work.
<p>content</p>
would become
<p><span>content</span></p>
Absolutely positioned element
Changing the element position to be absolute should also work:
#two { position: absolute; }
If you can't statically change the markup or the style, you can always change them dynamically through JavaScript.
(absolutely positioned element)
var realWidth = $("#two").css("position", "absolute").width();
(float)
var realWidth = $("#two").css("float", "left").width();
(inline-block element)
var t = $("#two").html();
var realWidth = $("#two")
.empty()
.append($("<span>").html(t))
.width();
Apply word-wrap: break-word; to it.. so the word will break and there won't be any text going out of the container... btw you can't check the width of the text which is going out of the container.
Example
Update: You can check if the width of text in it is bigger than the width of the container like this
As others have pointed out, changing the position of the element to absolute also works.
Doing this will result in an inline-style which can mess with your css afterwards if you don't watch out. Here is a solution to get rid of the inline style again.
//Change position to absolute
$('#two').css("position", "absolute");
var textWidth = $('#two').width();
//Get rid of the inline style again
$('#two').removeStyle("position");
//Plugin format
(function ($) {
$.fn.removeStyle = function (style) {
var search = new RegExp(style + '[^;]+;?', 'g');
return this.each(function () {
$(this).attr('style', function (i, style) {
return style.replace(search, '');
});
});
};
}(jQuery));
The element itself is constrained to 200px, but the text inside spills out. If you insert a span (or any other inline element) inside the P tag it works fine.
http://jsfiddle.net/will/vv68y/5/
Hope that helps :)

jQuery: Get height of hidden element in jQuery

I need to get height of an element that is within a div that is hidden. Right now I show the div, get the height, and hide the parent div. This seems a bit silly. Is there a better way?
I'm using jQuery 1.4.2:
$select.show();
optionHeight = $firstOption.height(); //we can only get height if its visible
$select.hide();
You could do something like this, a bit hacky though, forget position if it's already absolute:
var previousCss = $("#myDiv").attr("style");
$("#myDiv").css({
position: 'absolute', // Optional if #myDiv is already absolute
visibility: 'hidden',
display: 'block'
});
optionHeight = $("#myDiv").height();
$("#myDiv").attr("style", previousCss ? previousCss : "");
I ran into the same problem with getting hidden element width, so I wrote this plugin call jQuery Actual to fix it. Instead of using
$('#some-element').height();
use
$('#some-element').actual('height');
will give you the right value for hidden element or element has a hidden parent.
Full documentation please see here. There is also a demo include in the page.
Hope this help :)
You are confuising two CSS styles, the display style and the visibility style.
If the element is hidden by setting the visibility css style, then you should be able to get the height regardless of whether or not the element is visible or not as the element still takes space on the page.
If the element is hidden by changing the display css style to "none", then the element doesn't take space on the page, and you will have to give it a display style which will cause the element to render in some space, at which point, you can get the height.
I've actually resorted to a bit of trickery to deal with this at times. I developed a jQuery scrollbar widget where I encountered the problem that I don't know ahead of time if the scrollable content is a part of a hidden piece of markup or not. Here's what I did:
// try to grab the height of the elem
if (this.element.height() > 0) {
var scroller_height = this.element.height();
var scroller_width = this.element.width();
// if height is zero, then we're dealing with a hidden element
} else {
var copied_elem = this.element.clone()
.attr("id", false)
.css({visibility:"hidden", display:"block",
position:"absolute"});
$("body").append(copied_elem);
var scroller_height = copied_elem.height();
var scroller_width = copied_elem.width();
copied_elem.remove();
}
This works for the most part, but there's an obvious problem that can potentially come up. If the content you are cloning is styled with CSS that includes references to parent markup in their rules, the cloned content will not contain the appropriate styling, and will likely have slightly different measurements. To get around this, you can make sure that the markup you are cloning has CSS rules applied to it that do not include references to parent markup.
Also, this didn't come up for me with my scroller widget, but to get the appropriate height of the cloned element, you'll need to set the width to the same width of the parent element. In my case, a CSS width was always applied to the actual element, so I didn't have to worry about this, however, if the element doesn't have a width applied to it, you may need to do some kind of recursive traversal of the element's DOM ancestry to find the appropriate parent element's width.
Building further on user Nick's answer and user hitautodestruct's plugin on JSBin, I've created a similar jQuery plugin which retrieves both width and height and returns an object containing these values.
It can be found here:
http://jsbin.com/ikogez/3/
Update
I've completely redesigned this tiny little plugin as it turned out that the previous version (mentioned above) wasn't really usable in real life environments where a lot of DOM manipulation was happening.
This is working perfectly:
/**
* getSize plugin
* This plugin can be used to get the width and height from hidden elements in the DOM.
* It can be used on a jQuery element and will retun an object containing the width
* and height of that element.
*
* Discussed at StackOverflow:
* http://stackoverflow.com/a/8839261/1146033
*
* #author Robin van Baalen <robin#neverwoods.com>
* #version 1.1
*
* CHANGELOG
* 1.0 - Initial release
* 1.1 - Completely revamped internal logic to be compatible with javascript-intense environments
*
* #return {object} The returned object is a native javascript object
* (not jQuery, and therefore not chainable!!) that
* contains the width and height of the given element.
*/
$.fn.getSize = function() {
var $wrap = $("<div />").appendTo($("body"));
$wrap.css({
"position": "absolute !important",
"visibility": "hidden !important",
"display": "block !important"
});
$clone = $(this).clone().appendTo($wrap);
sizes = {
"width": $clone.width(),
"height": $clone.height()
};
$wrap.remove();
return sizes;
};
Building further on Nick's answer:
$("#myDiv").css({'position':'absolute','visibility':'hidden', 'display':'block'});
optionHeight = $("#myDiv").height();
$("#myDiv").css({'position':'static','visibility':'visible', 'display':'none'});
I found it's better to do this:
$("#myDiv").css({'position':'absolute','visibility':'hidden', 'display':'block'});
optionHeight = $("#myDiv").height();
$("#myDiv").removeAttr('style');
Setting CSS attributes will insert them inline, which will overwrite any other attributes you have in your CSS file. By removing the style attribute on the HTML element, everything is back to normal and still hidden, since it was hidden in the first place.
You could also position the hidden div off the screen with a negative margin rather than using display:none, much like a the text indent image replacement technique.
eg.
position:absolute;
left: -2000px;
top: 0;
This way the height() is still available.
I try to find working function for hidden element but I realize that CSS is much complex than everyone think. There are a lot of new layout techniques in CSS3 that might not work for all previous answers like flexible box, grid, column or even element inside complex parent element.
flexibox example
I think the only sustainable & simple solution is real-time rendering. At that time, browser should give you that correct element size.
Sadly, JavaScript does not provide any direct event to notify when element is showed or hidden. However, I create some function based on DOM Attribute Modified API that will execute callback function when visibility of element is changed.
$('[selector]').onVisibleChanged(function(e, isVisible)
{
var realWidth = $('[selector]').width();
var realHeight = $('[selector]').height();
// render or adjust something
});
For more information, Please visit at my project GitHub.
https://github.com/Soul-Master/visible.event.js
demo: http://jsbin.com/ETiGIre/7
Following Nick Craver's solution, setting the element's visibility allows it to get accurate dimensions. I've used this solution very very often. However, having to reset the styles manually, I've come to find this cumbersome, given that modifying the element's initial positioning/display in my css through development, I often forget to update the related javascript code. The following code doesn't reset the styles per say, but removes the inline styles added by javascript:
$("#myDiv")
.css({
position: 'absolute',
visibility: 'hidden',
display: 'block'
});
optionHeight = $("#myDiv").height();
optionWidth = $("#myDiv").width();
$("#myDiv").attr('style', '');
The only assumption here is that there can't be other inline styles or else they will be removed aswell. The benefit here, however, is that the element's styles are returned to what they were in the css stylesheet. As a consequence, you can write this up as a function where an element is passed through, and a height or width is returned.
Another issue I've found of setting the styles inline via js is that when dealing with transitions through css3, you become forced to adapt your style rules' weights to be stronger than an inline style, which can be frustrating sometimes.
By definition, an element only has height if it's visible.
Just curious: why do you need the height of a hidden element?
One alternative is to effectively hide an element by putting it behind (using z-index) an overlay of some kind).
In my circumstance I also had a hidden element stopping me from getting the height value, but it wasn't the element itself but rather one of it's parents... so I just put in a check for one of my plugins to see if it's hidden, else find the closest hidden element. Here's an example:
var $content = $('.content'),
contentHeight = $content.height(),
contentWidth = $content.width(),
$closestHidden,
styleAttrValue,
limit = 20; //failsafe
if (!contentHeight) {
$closestHidden = $content;
//if the main element itself isn't hidden then roll through the parents
if ($closestHidden.css('display') !== 'none') {
while ($closestHidden.css('display') !== 'none' && $closestHidden.size() && limit) {
$closestHidden = $closestHidden.parent().closest(':hidden');
limit--;
}
}
styleAttrValue = $closestHidden.attr('style');
$closestHidden.css({
position: 'absolute',
visibility: 'hidden',
display: 'block'
});
contentHeight = $content.height();
contentWidth = $content.width();
if (styleAttrValue) {
$closestHidden.attr('style',styleAttrValue);
} else {
$closestHidden.removeAttr('style');
}
}
In fact, this is an amalgamation of Nick, Gregory and Eyelidlessness's responses to give you the use of Gregory's improved method, but utilises both methods in case there is supposed to be something in the style attribute that you want to put back, and looks for a parent element.
My only gripe with my solution is that the loop through the parents isn't entirely efficient.
One workaround is to create a parent div outside the element you want to get the height of, apply a height of '0' and hide any overflow. Next, take the height of the child element and remove the overflow property of the parent.
var height = $("#child").height();
// Do something here
$("#parent").append(height).removeClass("overflow-y-hidden");
.overflow-y-hidden {
height: 0px;
overflow-y: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent" class="overflow-y-hidden">
<div id="child">
This is some content I would like to get the height of!
</div>
</div>
Here's a script I wrote to handle all of jQuery's dimension methods for hidden elements, even descendants of hidden parents. Note that, of course, there's a performance hit using this.
// Correctly calculate dimensions of hidden elements
(function($) {
var originals = {},
keys = [
'width',
'height',
'innerWidth',
'innerHeight',
'outerWidth',
'outerHeight',
'offset',
'scrollTop',
'scrollLeft'
],
isVisible = function(el) {
el = $(el);
el.data('hidden', []);
var visible = true,
parents = el.parents(),
hiddenData = el.data('hidden');
if(!el.is(':visible')) {
visible = false;
hiddenData[hiddenData.length] = el;
}
parents.each(function(i, parent) {
parent = $(parent);
if(!parent.is(':visible')) {
visible = false;
hiddenData[hiddenData.length] = parent;
}
});
return visible;
};
$.each(keys, function(i, dimension) {
originals[dimension] = $.fn[dimension];
$.fn[dimension] = function(size) {
var el = $(this[0]);
if(
(
size !== undefined &&
!(
(dimension == 'outerHeight' ||
dimension == 'outerWidth') &&
(size === true || size === false)
)
) ||
isVisible(el)
) {
return originals[dimension].call(this, size);
}
var hiddenData = el.data('hidden'),
topHidden = hiddenData[hiddenData.length - 1],
topHiddenClone = topHidden.clone(true),
topHiddenDescendants = topHidden.find('*').andSelf(),
topHiddenCloneDescendants = topHiddenClone.find('*').andSelf(),
elIndex = topHiddenDescendants.index(el[0]),
clone = topHiddenCloneDescendants[elIndex],
ret;
$.each(hiddenData, function(i, hidden) {
var index = topHiddenDescendants.index(hidden);
$(topHiddenCloneDescendants[index]).show();
});
topHidden.before(topHiddenClone);
if(dimension == 'outerHeight' || dimension == 'outerWidth') {
ret = $(clone)[dimension](size ? true : false);
} else {
ret = $(clone)[dimension]();
}
topHiddenClone.remove();
return ret;
};
});
})(jQuery);
If you've already displayed the element on the page previously, you can simply take the height directly from the DOM element (reachable in jQuery with .get(0)), since it is set even when the element is hidden:
$('.hidden-element').get(0).height;
same for the width:
$('.hidden-element').get(0).width;
(thanks to Skeets O'Reilly for correction)

Categories