0

Im doing a website through WordPress. I implemented active menu on scroll following this post, because of this.

I made it work, but becuase I'm using links instead of the id on the 'href' ("http://wordpress/#aboutus" instead of #aboutus) now have some problems. Some items on the nav-bar have exterior pages and scrolling doesn't add class to them.

CODE:

Menu Items:

var lastId,
  topMenu = $("#mainnav"),
  topMenuHeight = topMenu.outerHeight()+15,
  // All list items
  menuItems = topMenu.find("a"),
  // Anchors corresponding to menu items
  scrollItems = menuItems.map(function(){

    ////////// temp
    var temp = $(this).attr("href"); 
    console.log('temp', temp ); // Output example: "http://localhost/wordpress/#aboutus"

    ////////// ID
    var ID
    if (temp.indexOf('#') > -1) { // If link = "http://localhost/wordpress/#aboutus"
      ID = temp.split('#').pop(); // Output: "aboutus"       
    } else { 
      ID = temp.split('/').pop(); // if doesn't have "#"
    }
    console.log('ID', ID );

    ///////// item
    var item = temp.split('/').pop();

    if(!ID){
      console.log('ID undefined');
      var item = $('body');
    } else {
      var item = $('#'+ID);
    }
    console.log('item', item );

    if (item.length) { return item; }
  });

Scroll Action:

// Bind to Control
$(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 : "";
console.log("cur", cur);
console.log("id", id);
if (lastId !== id) {
  lastId = id;
  // Set/remove active class
  menuItems
    .parent().removeClass("current-menu-item")
    .end().filter("[href='http://localhost/wordpress/#"+id+"']").parent().addClass("current-menu-item");
   }
 });

How can I remove the ones that have no "#" or add class to the other pages and not being removed by scroll?

Silvestre
  • 59
  • 1
  • 11

1 Answers1

1

Ok I've changed

menuItems = topMenu.find('a[href*="#"]')

So it will get all anchors (a) that contains # in href.

Silvestre
  • 59
  • 1
  • 11