Search code examples
jquerywordpressnavigationsinglepagescrollspy

Wordpress single page navigation and jQuery scrollspy


Hi !

I have to create a website for the company were i'm working :)

My problem :

I created http://webl.eu/wordpress/ with Wordpress, it's a child theme from "Twenty Thirteen".

I would like to make the navigations li or a changing when the user scrolls to the corresponding element. I found this script :

(function($){

  var sections = [];
  var id = false;
  var $navbar = $('#navigation_desktop .navigation');
  var $navbara = $('a', $navbar);

  $navbara.click(function(e){
    e.preventDefault();
    $('html, body').animate({
      scrollTop: $($(this).attr('href')).offset().top - $navbar.height()
    });
    hash($(this).attr('href'));
  });

  $navbara.each(function(){
    sections.push($($(this).attr('href'))); // !!!erreur ici!!!
  });

    console.log(sections);
    
  $(window).scroll(function(e){
    var scrollTop = $(this).scrollTop() + ($(window).height() / 2)
    for(var i in sections){
      var section = sections[i];
      if (scrollTop > section.offset().top) {  // !!!erreur ici!!!
        scrolled_id = section.attr('id');
      }
    }
    if (scrolled_id !== id) {
      id = scrolled_id
      $navbara.removeClass('current');
      $('a[href="#' + id + '"]', $navbar).addClass('current');
    }
  });

})(jQuery);


hash = function(h) {
  if (history.pushState) {
    history.pushState(null, null, h);
  }else{
    location.hash = h;
  }
}

I think it should work...but it doesn't :(

Thanks,

Léo


Solution

  • I solved my problem :

    It's pretty easy : This script doesn't work if there is anything else than anchors in the menu !

    Hope it will be useful to you ;)

    Bye