How to activate event when you reach a certain point on the page with javascript or jquery?

3

You see, I have a menu on a one-page site, in which when you click on a menu item you go down to the indicated section and the selected menu item is underlined, but I need to make scroll and be in That section also underlines the element, could you help me?

This is the site

example page

    
asked by Michel Novellino 20.06.2017 в 03:02
source

3 answers

1

You can also create a kind of waypoints; that is, when it reaches a certain element, trigger a previously associated handler. You can create your own code for this or use a library like Waypoints .

const waypoints = [
  {
    id: 'about',
    handler(direction) { console.log('About'); }
  },
  {
    id: 'contact',
    handler(direction) { console.log('Contact'); }
  }
];


waypoints.forEach(({ id, handler }) => (
  new Waypoint({
    element: document.getElementById(id),
    handler,
    offset: 20 // añade un margen superior opcional
  })
));
.spacer {
  height: 200px;
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/noframework.waypoints.min.js"></script>

<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>

<h2 id="home">Home</h2>
<div class="spacer"></div>
<h2 id="about">About</h2>
<div class="spacer"></div>
<h2 id="contact">Contact</h2>
<div class="spacer"></div>
<div class="spacer"></div>
    
answered by 20.06.2017 / 15:31
source
1

The example that you put in concrete is a WordPress page in which the jQuery Smooth Scroll plugin

To do it yourself you should control the event scroll of the container element on which the scroll will be made:

 // Únicamente javascript (sin librerías)
 scrollableElement.addEventListener('scroll', scrollHandler);

 // o utilizando jQuery
 $(scrollableElement).scroll(scrollHandler);

In the scrollHandler function you can obtain the position of each element and, if you have reached the top position, activate the menu option.

Here is an example with jQuery:

$(function(){
  // div con el contenido
  var $content = $('#content');
  // barra de navegación
  var $nav = $('#nav');
  
  // secciones
  var secciones = [
    { menu: $('#intro'), content: $('#secIntro') },
    { menu: $('#ap1'), content: $('#secAp1') },
    { menu: $('#ap2'), content: $('#secAp2') },
    { menu: $('#ap3'), content: $('#secAp3') },
    { menu: $('#ap4'), content: $('#secAp4') }
  ];
  
  
  // Al hacer scroll
  $content.scroll(function(){
    // Quitamos la clase de todas las opciones de menu
    $nav.find('a').removeClass('active');
    // Recorremos las secciones de abajo a arriba
    // Activamos la primera cuya posición sea 40 o menor (ha llegado a la parte superior)
    // Le damos un margen de 40 para que no sea necesario que llegue hasta el borde
    for (var i=secciones.length -1; i >= 0; i--){
      // Posición superior de la sección
      var top = secciones[i].content.offset().top;
      // Si ha llegado arriba activamos el menú y salimos
      if (top <= 40){
        secciones[i].menu.addClass('active');
        return;
      }
    }
    // Si no ha llegado ninguna arriba activamos la intro
    $('#intro').addClass('active');
  });
});
html, body{
  height: 95%;
  margin: 0;
}
#nav{
  padding: 5px;
}
#nav a{
  text-decoration: none;
  color: #666666;
}
#nav a:hover {
  color: #000000;
}
#nav a.active{
  color: #cc3333;
}
#content{
  overflow-y: scroll;
  height: 95%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nav">
  <a id="intro" class="menu active" href="#secIntro">Introducción</a>
  <a id="ap1" class="menu" href="#secAp1">Apartado 1</a>
  <a id="ap2" class="menu" href="#secAp2">Apartado 2</a>
  <a id="ap3" class="menu" href="#secAp3">Apartado 3</a>
  <a id="ap4" class="menu" href="#secAp4">Apartado 4</a>
</div>
<div id="content">
  <div id="secIntro">
    <h3>Introducción</h3>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
  </div>
  <div id="secAp1">
    <h3>Apartado 1</h3>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
  </div>
  <div id="secAp2">
    <h3>Apartado 2</h3>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
  </div>
  <div id="secAp3">
    <h3>Apartado 3</h3>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
  </div>
  <div id="secAp4">
    <h3>Apartado 4</h3>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
    <p>....</p>
  </div>
</div>
    
answered by 20.06.2017 в 09:02
1

You can use an offset, something like:

$(document).ready(function (){

var altura = $("#inicio").offset().top;
var altura2 = $("#section2").offset().top;

$(window).scroll(function(){

   if($(window).scrollTop() >= altura + 400) {

  $(".boton1").css({"font-weight": "600"});

}else{

  $(".boton1").css({"font-weight": "400"});

}

   if($(window).scrollTop() >= altura2) {

  $(".boton2").css({"font-weight": "600"});
  $(".boton1").css({"font-weight": "400"});

}else{

  $(".boton2").css({"font-weight": "400"});

}

   });
   
   $(".boton1").click(function(){

$("html, body").animate({scrollTop: altura},500);

  });
   
   $(".boton2").click(function(){

$("html, body").animate({scrollTop: altura2},500);

  });
 
});
* {
 padding: 0;
 margin: 0;
 font-family: sans-serif;
}

html, body {
 width: 100%;
 height: 700px;
}

.section {
  height: 700px;
  width: 100%;
}

nav {
 position: fixed;
 width: 100%;
 height: 50px;
 text-align: center;
}

nav ul {
  list-style: none;
}

nav ul li {
  display: inline-block;
}

nav ul li a {
  display: block;
  padding: 16px 20px;
  text-decoration: none;
  text-transform: uppercase;
  color: rgb(170, 92, 122);
}

nav ul li a:hover {
  font-weight: 600;
  color: rgb(148, 61, 95);
}

#section2 {
  background-color: lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<nav>
  <ul>
    <li><a class="boton1" href="#inicio">Botón uno</a></li>
    <li><a class="boton2" href="#section2">Botón dos</a></li>
  </ul>
</nav>
<section class="section" id="inicio">

</section>
<section class="section" id="section2">

</section>

Short explanation: when the document is ready - > ( $(document).ready(); ) I apply a variable with the offset function - > ( var altura = $(".section").offset().top ) to determine the height in top of the label or class in terms of the window, and then within the function ready() I apply a function scroll() in the window $(window) and in I add my if so that if the window has a scroll at the top height and is greater than or equal to the previous variable - > ( if($(window).scrollTop() >= altura){ aqui las funciones} ) I apply the necessary functions to animate, change, etc. HTML tags you want, in this case, I changed the CSS values of the tags. If you want to know more about the subject or do not understand well, I recommend you go deeper into the JQuery and study the functions offset() and scroll() .

As an additional data, you can add as many variables with the function offset() as sections and buttons of the menu you have, so that within the function scroll() you can add more if/else . Also outside the function scroll() added other functions so that when you click on the menu buttons, move with an animation and not simply appear at once in the section.

    
answered by 20.06.2017 в 03:17