1

this is my first jquery code.Here i am trying to do a content loading mechanism using jquery ajax. It supposed to load content in a container div.But it is navigating me to a whole new page.I want that the 'a' tag does not navigate me to another page.What i am doing wrong here ?How i can achieve that?

<html>

<body>
<ul>
<li><a href='about.html'>about</a></li>
<li><a href='faq.html'>faq</a></li>
</ul>
<div id='content'></div>
<script src='c/xampp/htdocs/practice/jquery/jquery.js'></script>
<script>
$('a').click(function(){
       var page=$(this).attr('href');
       $('#content').load(page);
       return false;
});
</script>
</body>
</html>
4
  • 1
    c/xampp/htdocs/practice/jquery/jquery.js should be c:/xampp/htdocs/practice/jquery/jquery.js assuming you are on a windows machine Commented Dec 21, 2015 at 1:37
  • changing path name didn't work. :( may be a problem in my jquery.js file Commented Dec 21, 2015 at 1:45
  • 2
    If you're having trouble with getting your jQuery file to load, you could always use a CDN instead, such as code.jquery.com/jquery-2.1.4.min.js Just copy the full link into the <script> tag's src attribute. Commented Dec 21, 2015 at 1:50
  • adding type attribute inside script tag solved my problem. what a silly mistake :/ Commented Dec 21, 2015 at 1:55

1 Answer 1

3

You are clicking on a link which should take you to the page before you do anything. Use event.preventDefault() to prevent this.

$('a').click(function(event){
       event.preventDefault();
       var page=$(this).attr('href');
       $('#content').load(page);
       return false;
});

Also you should include jQuery using your localhost url : (I guess you are using proper link for the page?)

 <script src='http://localhost/practice/jquery/jquery.js'></script>

Remember, type="text/javascript" definition is not necessary in html5. But you didn't use the html5 doctype definition. Use this at the top of everything in the page.

<!DOCTYPE html>
Sign up to request clarification or add additional context in comments.

5 Comments

still doesn't work .i have used an alert inside the function.It haven't triggered . I assume there is a problem in my jquery download file. :(
Check the edited part of my answer. Looks like you haven't included the jQuery properly.
do i need to use http here ?
adding type='text/javascript' attribute in script tage made it work :/ :))
Hm. That is actually not necessary for html5. But I know now why it didn't work. You didn't include doctype definition in the beginning. I will just edit my answer to add that. Otherwise you may have miss more features of html5.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.