clarinet
clarinet

Reputation: 103

JQuery only works with alert

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?

Upvotes: 0

Views: 1973

Answers (1)

Rob W
Rob W

Reputation: 9142

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');
      }
    });
  });
});

Upvotes: 2

Related Questions