I’m trying to make a single page where content will be loaded instead of redirecting a user to a new page once a link is clicked . I’ve tried this using ajax but i’m still redirected to another page
Here is what i have done so far
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Page</title>
</head>
<body>
<div class="header">
<p> welcome page</p>
<nav>
<ul>
<li><a href="home.html">home</a> </li>
<li> <a href="about.html">About</a> </li>
</ul>
</nav>
<p>Hello page</p>
<div id="content">
<p>Content is loaded here</p>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("ul.nav li a").click(function(e) {
e.preventDefault();
var url = $(this).attr('href'); //get the link you want to load data from
$.ajax({
type: 'GET',
url: url,
success: function(data) {
$("#content").html(data);
}
});
});
});
</script>
</body>
</html>
Can anyone help please !
2
Answers
A couple of issues.
First, the jquery selector is not correct so you are not attaching the click listener to the right element,
nav li a
Second, since you are using the href attribute that the browser will be following, you need to
return false
in your click listener to prevent such behaviorThe selector you’re using is not correct;
nav
is an element, not a class. So you can use any of the following:You also need to include jQuery – be sure the following appears before your JS:
Lastly your HTML is malformed; you do not have a closing tag for
div.header
:which can be inserted just before the script tag(s).
The rest of your JS code is correct and should work once you correct the selector but I would suggest you consider using the
.load()
method for it’s conciseness: