Reputation: 218877
I'm using the following code to fadeOut
and fadeIn
content divs on a page (jsfiddle here)...
HTML:
<ul>
<li><a id="indexNav" href="index.html">Home</a></li>
<li><a id="aboutNav" href="about.html">About</a></li>
</ul>
<div id="indexContent">
This is the main page content.
</div>
<div id="aboutContent">
This is the about page content.
</div>
CSS:
ul {
float: left;
display: block;
margin-top: 50px;
margin-left: 0px;
}
ul li {
list-style: none;
display: block;
margin-top: 5px;
}
ul li a {
display: block;
height: 20px;
width: 50px;
margin: 0px;
background: #7d5900;
color: white;
text-decoration: none;
text-align: center;
}
div {
width: 300px;
height: 200px;
margin: auto;
margin-top: 70px;
color: white;
background-color: rgba(0, 36, 125, 0.5);
}
#aboutContent {
display: none;
}
JavaScript:
$('#indexNav').click(function() {
$('#aboutContent').fadeOut('fast');
$('#indexContent').fadeIn('fast');
return false;
});
$('#aboutNav').click(function() {
$('#indexContent').fadeOut('fast');
$('#aboutContent').fadeIn('fast');
return false;
});
As demonstrated in the jsfiddle (at least in Firefox 9.0.1 and IE 9 on Windows 7), when clicking back and forth between the links to show/hide the elements in question, there is a bit of a page-wide flicker as the elements animate. Basically, the div
moves far down the page, which causes a scrollbar to appear and push the div
a little to the left, then it returns to normal when the animation finishes.
Not being an expert in CSS by any means, I've just been sort of tinkering with this to try to achieve a simple fade-out/fade-in effect (using jQuery, naturally). So I'm wondering if there's a more correct way to do this or if I'm making some kind of fundamental mistake in my design that's just not known to me.
Any ideas on what might be causing this flicker and how to correct it?
Upvotes: 5
Views: 6883
Reputation: 2784
$('#indexNav').click(function() {
$('#aboutContent').fadeOut('fast',function(){
$('#indexContent').fadeIn('fast');
});
return false;
});
$('#aboutNav').click(function() {
$('#indexContent').fadeOut('fast',function(){
$('#aboutContent').fadeIn('fast');
});
return false;
});
Upvotes: 4
Reputation: 30099
This occurs because your elements are displayed relatively. That means that when both are present on the screen, they move each other around. When you do a cross-fade, which is essentially what you are doing, they will both be on the screen for a time. You need to absolutely position the elements to occupy the same space.
#aboutContent, #indexContent {
position: absolute;
top: 10px;
left: 50px;
}
Example: http://jsfiddle.net/2TDj5/
You can put the elements in a wrapper div, which will allow you to position them relative to the page, but absolute with regard to each other. Just make sure that you explicitly set the wrapper to display: relative
.
Example: http://jsfiddle.net/2TDj5/1/
Upvotes: 6