Skip to content

Instantly share code, notes, and snippets.

@TrywaR
Last active May 17, 2018 14:03
Show Gist options
  • Save TrywaR/fe5c107d4b9460fe149d9d83cfda5c7c to your computer and use it in GitHub Desktop.
Save TrywaR/fe5c107d4b9460fe149d9d83cfda5c7c to your computer and use it in GitHub Desktop.
[ ScrollMenuBeautiful ] jQuery
/*___________________ Скрольная магия __________________*/
$(document).on ('click', '#up', function(event) {
event.preventDefault();
$('html, body').stop().animate({
scrollTop: 0
}, 600)
})
if ($(document).scrollTop() > 100) {
$('header').addClass('_fixed_')
$('#up').addClass('_fixed_')
}else{
$('header').removeClass('_fixed_')
$('#up').removeClass('_fixed_')
}
// сохраняем высоту шапки
var headerHeight = $('header').height()
// обработка скроллинга (изменение активного элемента меню)
$(document).scroll(function(){
var offsets = []
if ($(document).scrollTop() > 100) {
$('header').addClass('_fixed_')
$('#up').addClass('_fixed_')
}else{
$('header').removeClass('_fixed_')
$('#up').removeClass('_fixed_')
}
$('nav li a').each(function(index, element){
// собираем в массиве offsets смещения разделов относительно начала документа
offsets.push( $('' + $(element).attr('href') +'').offset().top )
})
// дополняем массив еще одним елементом- высота всего документа
offsets.push($(document).height())
// изменяем активный пункт как только область зашла за полэкрана: $(window).height() / 2
var docScroll = $(document).scrollTop() + headerHeight + $(window).height() / 2
for (var i = 0; i < offsets.length - 1; i++) {
if (docScroll >= offsets[i] && docScroll < offsets[i+1]) {
$('nav li._active_').removeClass('_active_')
$('nav li').eq(i).addClass('_active_')
$('section').removeClass('_active_')
$($('nav li:eq('+i+') a').attr('href')).addClass('_active_')
break
}
}
})
/*Автоскролл*/
$(document).on ('click', 'nav li a', function(e){
e.preventDefault();
var anchor = $(this).attr('href')
var scroll = $(''+anchor+'').offset().top
$('html, body').stop().animate({
scrollTop: scroll
}, 600)
})
/*///////////////////////////////////////////////////////*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment