0

This code only works with the alert. Removing the alert will not execute the code after it:

$(document).ready(function() {
  $('#topmenu').load('/include/topmenu.htm');
});

$(window).load(function() {
  var pagePath = window.location.pathname;
  var pageSplit = pagePath.split('/');
  var pageSection = pageSplit[1];
  alert('hi');

  $('#topmenu a').each(function() {
    var path = this.pathname;
    var section = path.split('/')[1];
    if (section == pageSection) {
      $(this).addClass('selected');
    }
  });
});
 <a href="/section1/index.asp">Section1</a>
<a href="/section2/index.asp">Section2</a>
<a href="/section3/index.asp">Section3</a>

It seems like the code that follows the alert only recognizes the pageSection value when the alert is there, otherwise, the value is not defined.

Is the $('#topmenu a') selector executing before the preceding pageSection code has enough time to run? What is the proper way to handle this situation?

Rob W
  • 9,134
  • 1
  • 30
  • 50
clarinet
  • 113
  • 1
  • 9
  • 1
    Alert probably stops any further action long enough for page to fully load. You should run `$('#topmenu a').each` only after page loading is completed and `#topmenu a` element is available on your page. – Marko Gresak Mar 22 '15 at 02:15
  • See http://stackoverflow.com/a/8396457/2055998 – PM 77-1 Mar 22 '15 at 02:18

1 Answers1

2

This is happening because your menu isn't loading fast enough. You should apply a callback to load() instead.

$(document).ready(function() {
  $('#topmenu').load('/include/topmenu.htm', function() {
    var pagePath = window.location.pathname;
    var pageSplit = pagePath.split('/');
    var pageSection = pageSplit[1];

    $('#topmenu a').each(function() {
      var path = this.pathname;
      var section = path.split('/')[1];
      if (section == pageSection) {
        $(this).addClass('selected');
      }
    });
  });
});
Rob W
  • 9,134
  • 1
  • 30
  • 50
  • Thank you, that works. Does it execute the callback after topmenu loads? – clarinet Mar 26 '15 at 01:03
  • Yes, that's what the callback is for. It's fired only after `load()` completes. In some instances, you should pass parameters into the callback and check the response to ensure it's a valid response/expected data. – Rob W Mar 27 '15 at 15:28