hstur hstur -4 years ago 87
jQuery Question

jQuery fadeIn and than move to div

I am trying to make function, which fade in

div
on click and than it should move to that
div
. But it doesn't work, with first click
div
appears and I have to click one more time to move there.
Could someone help me out please?
https://jsfiddle.net/qzdxf478/

<a href="#princip-detail" class="showDetail">Continue</a>


<script>
$(document).ready(function() {
$('.showDetail').click(function() {
$('#princip-detail').fadeIn();
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {

var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
</script>

Answer Source

Prevent the default action of the anchor you click using e.preventDefault();. Don't forget to include the jQuery library. Run the snippet below to see it in action:

$(document).ready(function() {
  $('.showDetail').click(function(e) {
    e.preventDefault();
    $('#princip-detail').fadeIn();
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});
#principy {
  width: 100%;
  height: auto;
  min-height: 100%;
  background: url('main-bg.jpg') no-repeat center center;
  background-size: cover;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
  z-index: 20;
}

#princip-detail {
  width: 100%;
  position: absolute;
  top: 100%;
  left: 0;
  height: auto;
  min-height: 100%;
  background: #f00 url("page-bg.jpg") no-repeat center center;
  overflow: hidden;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="principy">
  <div class="princip-topleft">
    <h2><a href="#princip-detail" class="showDetail">Continue</a></h2>
  </div>

</div>

<div id="princip-detail">

</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download