Problems with scrollTop for anchors in HTML

0

I'm doing a page which when clicking on an option on the menu, it goes to an anchor of it. There's even good. When I use the following code in jquery for scrolling

$('nav a').click(function(e){               
        e.preventDefault();     //evitar el eventos del enlace normal
        enlace  = $(this).attr('href');
    $('html, body').animate({       
         scrollTop: $(enlace).offset().top
    }, 1000);
});

The following message appears on the console

  

Uncaught TypeError: Can not read property 'top' of undefined

In the examples I find online I see that they use it but it does not work for me.

    
asked by Carlos Cespedes 26.10.2018 в 22:27
source

1 answer

1

Use the offset () method and call the top property:

$('nav a').click(function(e){ 
e.preventDefault(); //evitar el eventos del enlace normal enlace = 
$(this).attr('href'); 
$('html, body').animate({ 
scrollTop: $(enlace).offset().top 
}, 
1000); 
});

The offset () method returns an object that contains 2 properties top and left and these contain an integer value specifying the position of an element.

That you have it right the problem is the element that is not being obtained with the selector that you use it is possible that nav is a class so instead of nav you should put .nav .

    
answered by 26.10.2018 / 22:43
source