Ermac Ermac - 7 months ago 23
Javascript Question

Fade out current and fade in anchor on JavaScript

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 content. For that, I must get the current page ID and the anchor

href
with JavaScript.

This is what I got so far: (Please note in the script that is a simple calling method that I don't know yet)



$(btn).click(function(e){
$(*/current page/*).fadeOut('slow', function(){
$(*/destiny page/*).fadeIn('slow');
});
});

#page2, #page3 {
display:none;
}

<div id="page1">
Page 1 Content
<br>
<a href="page2" id="btn">Show Page 2 and hide this page</a>
<br>
<a href="page3" id="btn">Show Page 3 and hide this page</a>
</div>

<div id="page2">
Page 2 Content
<br>
<a href="page1" id="btn">Show Page 1 and hide this page</a>
<br>
<a href="page3" id="btn">Show Page 3 and hide this page</a>
</div>

<div id="page3">
Page 3 Content
<br>
<a href="page1" id="btn">Show Page 1 and hide this page</a>
<br>
<a href="page2" id="btn">Show Page 2 and hide this page</a>
</div>





I really apreciate your help and efforts!

Answer

For referring a group of elements You need to use btn as class , id should be unique and can be use to refer single element.

// bind click event
$('.btn').click(function(e) { 
  // prevent default click event action
  e.preventDefault();
  // get id next page based on clicked element
  var next = $(this).attr('href');
  // get parent to hide and fadeout
  $(this).parent().fadeOut('slow', function() {
    // get element to show and fade in
    $('#' + next).fadeIn('slow');
  });
});
#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>