carlstrom96
carlstrom96

Reputation: 249

Customizing jQuery scrolling effect

I'm working on a website where I have made a simple scrolling effect using jQuery. Basically, I just have the page scroll to a specified section when the user clicks on one of the navigation links. I would like to customize this so that the header (which I'm using as my scrolling target) is not at the very top of the page. I want it more in the middle. Does anybody know how I can easily customize this? Below is my jQuery code.

jQuery Scroll effect

$('a[href*="#"]').on('click', function(e) {
e.preventDefault()

$('html, body').animate(
  {
    scrollTop: $($(this).attr('href')).offset().top,
  },
  500,
  'linear'
)
 });

Thank you!

Upvotes: 0

Views: 36

Answers (1)

Pinetree
Pinetree

Reputation: 637

The key is to calculate the offset, Try this:

$('a[href*="#"]').on('click', function(e) {
	e.preventDefault()

	var id = $(this).attr('href');
	var $element = $(id);
	var elementHeight = $element.height();
	var winHeight = $(window).height();
	var offset;
	if(elementHeight >= winHeight) //if element height > window height, just put the element to top place.
	{
		offset = 0;
	}
	else // else make it to the middle place of window.
	{
		offset = Math.round((elementHeight - winHeight) / 2);
	}

	$('html, body').animate(
	  {
	    scrollTop: $element.offset().top + offset,
	  },
	  500,
	  'linear'
	)
 });
body, html {
  padding: 0;
  margin: 0;
}

.nav-wrap {
  width: 100vw;
  position: fixed;
  background: rgba(0,0,0,0.5);
  padding: 10px;
}

.nav-wrap > a {
  color: #ffffff !important;
  padding: 10px;
}

section {
  display: block;
  width: 100vw;
}

#id1 {
  background: #ff0000;
  height: 50vh;
}
#id2 {
  background: #00ff00;
  height: 80vh;
}
#id3 {
  background: #ffff00;
  height: 120vh;
}
#id4 {
  background: #0000ff;
  height: 30vh;
}
#id5 {
  background: #000000;
  height: 60vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="nav-wrap">
  <a href="#id1">ID1</a>
  <a href="#id2">ID2</a>
  <a href="#id3">ID3</a>
  <a href="#id4">ID4</a>
  <a href="#id5">ID5</a>
</div>
<div class="section-wrap">
  <section id="id1"></section>
  <section id="id2"></section>
  <section id="id3"></section>
  <section id="id4"></section>
  <section id="id5"></section>
</div>

Upvotes: 1

Related Questions