I'm getting unpredictable results when calling jquery's css("display")
on an element; sometimes it's flex
, other times it is block
. What's strange is that this error is only present when I'm using jquery's show
/hide
, and the error happens about 50% of the time. What's even more strange is that I'm seeing these results before hide
even runs.
Update: It seems to also be tied to this google webfont css I'm including. If I remove the font the problem goes away. This is all very strange.
Here's a simplification of my code:
js:
$(document).ready(function () {
console.log("1 display: " + $("#foo").css("display"));
$("#foo").hide();
console.log("2 display: " + $("#foo").css("display"));
$("#foo").show();
console.log("3 display: " + $("#foo").css("display"));
});
html:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/JavaScript"
src="http://code.jquery.com/jquery-1.6.3.min.js"></script>
<script type="text/JavaScript" src="script.js"></script>
<link href='http://fonts.googleapis.com/css?family=Forum' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="foo" class="centerer">
<p>Hello!</p>
</div>
</body>
</html>
css:
#foo {
background: white url("bg.jpg") center no-repeat;
background-size: 100vw auto;
}
.centerer {
display: flex;
flex-flow: column nowrap;
align-items: center;
justify-content: center;
}
The correct behavior should print out:
1 display: flex
2 display: none
3 display: flex
But what I'm seeing about 50% of the time is:
1 display: block
2 display: none
3 display: block
Any ideas on what could be causing this? I want to know why.
In your bad output your initial value of display is block. This is not a bug with the show method.
Are you sure than your script is execute after the CSS calculation ?
Check your document structure :
<!DOCTYPE html>
<html>
<head>
<!-- css include/import -->
</head>
<body>
<!-- html body -->
<!-- script include/import -->
</body>
</html>
For JQuery hide() and show() functions to work properly (maintain original display value) the element should be part of the DOM at the point in time when function is called. Maybe Google Webfonts temporary unloads your content from DOM...
Problem can be reproduced like this:
https://jsfiddle.net/u442nsko/1
#foo {
display: flex;
}
$(document).ready(function () {
var my = $("<div id='foo'>......</div>")
console.log("1 display: " + my.css("display"));
my.hide();
console.log("2 display: " + my.css("display"));
my.show();
console.log("3 display: " + my.css("display"));
$("body").append(my);
console.log("4 display: " + my.css("display"));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With