Reputation: 438
I've got a simple problem that I don't know how to deal with it because I'm learning JavaScript
What I want to do is a link navigation to an anchor with fade in/out transition on CSS. For that, I must get the current page ID and the anchor href with JavaScript and trigger the CSS effect.
This is what I got so far:
$('.btn').click(function(e) {
e.preventDefault();
var next = $(this).attr('href');
$(this).parent().addClass('fadeout', function() {
setTimeout(function() {
$(this).parent().css('display', 'none');
}, 1000);
$('#' + next).css('display', 'block');
$('#' + next).addClass('fadein');
});
});
.fadeout {
opacity: 0;
transition: all 1000ms ease;
}
.fadein {
opacity: 1;
transition: all 1000ms ease;
}
#page2,
#page3 {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="page1">
Page 1 Content
<br>
<a href="page2" class="btn">Show Page 2 and hide this page</a>
<br>
<a href="page3" class="btn">Show Page 3 and hide this page</a>
</div>
<div id="page2">
Page 2 Content
<br>
<a href="page1" class="btn">Show Page 1 and hide this page</a>
<br>
<a href="page3" class="btn">Show Page 3 and hide this page</a>
</div>
<div id="page3">
Page 3 Content
<br>
<a href="page1" class="btn">Show Page 1 and hide this page</a>
<br>
<a href="page2" class="btn">Show Page 2 and hide this page</a>
</div>
Thank you in advance for helping me learning
Upvotes: 0
Views: 126
Reputation: 14308
There are a few things wrong with your code:
addClass
method just expects 1 parameter, so that second parameter (function) will never get called.this
inside your timeout callback is not what you think it is. this
behaves somewhat strange, and can be hard to grasp, especially when you are just starting out with javascript. I won't explain it here (plenty of info out there), but I would cache the value inside a variable outside the timeout function in this case.fadein
and the invisible ones a class fadeout
. That way you can just toggle both to switch the state.show()
and hide()
methods, so I would use those in stead of modifying the display
value yourself.fadeIn
and fadeOut
method as well, which are probably better suited here, but let's stick with you css animation here for sake of your "exercise". So with that said, you javascript would look something like this:
$('.btn').click(function(e) {
e.preventDefault();
var $target = $(this);
var $next = $('#' + $(this).attr('href'));
$target.parent().toggleClass('fadeout fadein');
setTimeout(function() {
$target.parent().hide();
$next.show();
$next.toggleClass('fadein fadeout');
}, 1000);
});
Have a look at the code in action: https://jsfiddle.net/rr7a7sL4/
Upvotes: 2