Здравствуйте!
У меня посты на сайте подгружаются с помощью Infinite scroll. Я подключил js файл, в котором плавный переход по якорям и изменение класса у ссылок при скролле.
Так вот при загрузке первого поста эти функции выполняются. Но как только подгрузился второй пост (и все следующие) - в нем уже не работает ни плавная прокрутка, ни изменение класса.
Вот js файл:
jQuery(document).ready(function($){
// Прокрутка на все якоря (#) и на a[name]. v1.1
$('a[href*="#"]').on('click.smoothscroll', function( e ){
var hash = this.hash,
_hash = hash.replace(/#/,''),
theHref = $(this).attr('href').replace(/#.*/, '');
if( theHref && location.href.replace(/#.*/,'') != theHref ) return; // не текущая страница
var $target = _hash === '' ? $('body') : $( hash + ', a[name="'+ _hash +'"]').first();
if( ! $target.length ) return;
e.preventDefault();
$('html, body').stop().animate({ scrollTop: $target.offset().top - 65 }, 400, 'swing', function(){
window.location.hash = target;
});
});
// Cache selectors
var lastId,
topMenu = $("#kcmenu"),
topMenuHeight = topMenu.outerHeight()+15,
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var item = $($(this).attr("href"));
if (item.length) { return item; }
});
// Bind to scroll
$(window).scroll(function(){
// Get container scroll position
var fromTop = $(this).scrollTop()+topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function(){
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href='#"+id+"']").parent().addClass("active");
}
});
});
Подскажите, пожалуйста, как можно его переделать, чтобы подружить с Infinite scroll?
$(document.body).on('click', 'a[href*="#"]', function(e) {
// ваш код
});
Вместо:
menuItems
.parent().removeClass("active")
Должно быть:
$("#kcmenu").find("a")
.parent().removeClass("active")
Это нужно потому что при обновлении DOM ваши скрипты должны видеть новые элементы. Без этого изменения скрипты видят только старые, потому на них ничего не действует.
Сборка персонального компьютера от Artline: умный выбор для современных пользователей