1

Is there a way to avoid "page jumping" if i use a "#"-Link tag? Do i need to use the hashchange event in order to solve the problem?

$(function() {
  $('nav a').click(function() {
    $('.job-details').fadeOut(400);
    $('#'+$(this).data('rel')).fadeIn(400);
  });    
});
.job-details {
  position: absolute;
  top: 50px;
  width: 400px;
  height: 200px;
  padding: 0 20px;
  border: 1px solid #ddd;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
  <a href="#job1" data-rel="job1">Job 1</a>
  <a href="#job2" data-rel="job2">Job 2</a>
  <a href="#job3" data-rel="job3">Job 3</a>
</nav>

<div class="job-details" id="job1">
  <p>Job 1</p>        
</div>
<div class="job-details" id="job2">
  <p>Job 2</p>        
</div>
<div class="job-details" id="job3">
  <p>Job 3</p>        
</div>
Turnip
  • 35,836
  • 15
  • 89
  • 111
simon
  • 33
  • 4

1 Answers1

0

You need to prevent the browsers default behaviour when a link is clicked by using event.preventDefault()

$(function() {
  $('nav a').click(function(e) {
    e.preventDefault();

    $('.job-details').fadeOut(400);
    $('#'+$(this).data('rel')).fadeIn(400);
  });    
});
.job-details {
  position: absolute;
  top: 50px;
  width: 400px;
  height: 200px;
  padding: 0 20px;
  border: 1px solid #ddd;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav>
  <a href="#job1" data-rel="job1">Job 1</a>
  <a href="#job2" data-rel="job2">Job 2</a>
  <a href="#job3" data-rel="job3">Job 3</a>
</nav>

<div class="job-details" id="job1">
  <p>Job 1</p>        
</div>
<div class="job-details" id="job2">
  <p>Job 2</p>        
</div>
<div class="job-details" id="job3">
  <p>Job 3</p>        
</div>
Turnip
  • 35,836
  • 15
  • 89
  • 111