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?