Scroll effectTo JS , make it work by clicking on <li> and not only on <a href="#">

Asked

Viewed 67 times

0

My problem is this, I am using the plugin scrollTo was all ok working on all elements I wanted on the site.

However they asked to change something in the menu, currently the effect only happens when I click on the tag <a href="#">, however asked to change, now everything has to happen when I click on <li>. Okay could involve the li within a a, but I would have a bigger job (I believe) than changing the JS, but not getting it, I already modified the code below a few times and it only worked when in html I put the href on the tag li (but it must be wrong this right).

Follows the code.

	$(function(){
	
		var wrapper = $("#wrapper"),
    $menu = $("#menu");
	
		$menu.on("click","a", function(){
			var $this = $(this),
					href = $(this).attr("href"),
		      topY = $(href).offset().top;
	
		    TweenLite.to(window, 2, {scrollTo:{y:topY, x:0}, ease:Cubic.easeIn});
	
		  return false;
		});
	
	});
nav#menu.menu
	ul
		li.icon-play
			a(href="#home")
		li.link-empresa
			a(href="#empresa") playlearn
		li.link-tecnologias
			a(href="#tecnologicas") tecnologia educacional
		li.link-cases
			a(href="#cases") portifólio
		li.link-contato
			a(href="#contato") contato

1 answer

0


I changed your code to be triggered by clicking on <li> and search using the .find() the element <a> inside him and retrieve his href:

$(function(){
	
		var wrapper = $("#wrapper"),
    $menu = $("#menu");
	
		$menu.on("click","li", function(){
			var este = $(this),
					href = $(this).find("a").attr("href"),
		      topY = $(href).offset().top;
	
		     $('html, body').animate({ scrollTop: topY }, 800);
	
		  return false;
		});
	
	});
.ex {
   height: 200px;
   background: #EEE;
   border: 1px solid #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<nav id="menu" class="menu">
<ul>
  <li class="icon-play">
    <a href="#home">HOME</a>
  </li>
  <li class="link-empresa">
    <a href="#empresa">playlearn</a>
  </li>
  <li class="link-tecnologias">
    <a href="#tecnologicas">tecnologia educacional</a>
  </li>
  <li class="link-cases">
    <a href="#cases">portifólio</a>
  </li>
  <li class="link-contato">
    <a href="#contato">contato</a>
  </li>
</ul>
</nav>

<div id="home" class="ex"></div>
<div id="empresa" class="ex"></div>
<div id="tecnologicas" class="ex"></div>
<div id="cases" class="ex"></div>
<div id="contato" class="ex"></div>

I changed the code to work using only jQuery, but this is according to your need/will.

  • Guy was just that, very basic and I was cracking my head =/ ... Thank you so much =D.

  • 1

    @Erick is not shaken that I have been for almost a decade breaking my head in the JS hahaha besides we are here to strengthen the community, I am happy to help you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.