I am using jquery to load a sidebar into each of my pages, the sidebar contains a list of story names, the date, and the content type (story, article, news, whatever) which is placed in an unordered list, when each page loads I use jquery’s .load() function to load the sidebar information into the current page’s unordered list, once the sidebar information has loaded I use another script which sets the href of the current story in the sidebar to #. The problem is that the piece of code that sets the href to # only works if I put an alert right before the function.
Here is the flow:
user clicks on a story (lets call the story nothing.html)
nothing.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../../../../css/reset.css">
<link rel="stylesheet" href="../../../../css/index.css">
<script type="text/javascript" src="../../../../js/jquery.js"></script>
<script type="text/javascript" src="../../../../js/storyLoadSidebar.js"></script>
<script type="text/javascript" src="../../../../js/disableLink.js"></script>
<title> Nothing </title>
</head>
<body>
<div id="container">
<div id="main">
<article>
<header>
<h3> Nothing Here </h3>
<time pubdate="pubdate"> July 19, 2011 </time>
</header>
<p> I said there was nothing here, yet. </p>
</article>
</div>
<div id="listWrapper">
<div id="storyList">
<ul></ul>
</div>
</div>
</div>
</body>
</html>
storyLoadSidebar.js
$(document).ready(function() {
$("ul").load("../../../../sidebar.html ul");
});
sidebar.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<ul>
<li>
<div class="catDate">
<p> Nothing </p>
<time pubdate="pubdate"> 2011-07-19 </time>
</div>
<div class="storyTitle">
<a id="nothing" href="stories/2011/07/19/nothing.html"> Nothing Here, Yet. </a>
</div>
</li>
</ul>
</body>
</html>
then finally the script to disable the link:
disableLink.js
$(document).ready(function() {
var fullPath = window.location.pathname;
var pageName = fullPath.substring(fullPath.lastIndexOf('/') + 1).replace('.html', '');
$('#' + pageName).attr('href', '#');
});
The entire thing only works of I add an alert to disableLink.js right before the href modification like so:
$(document).ready(function() {
var fullPath = window.location.pathname;
var pageName = fullPath.substring(fullPath.lastIndexOf('/') + 1).replace('.html', '');
alert('now it will work');
$('#' + pageName).attr('href', '#');
});
What is the problem here, why does it only work if I add in an alert?
The reason is
$("ul").load("...")takes some time to load.You can assign it a call back function so the next piece of code only runs when it is completed