Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
106
rated 0 times [  113] [ 7]  / answers: 1 / hits: 16258  / 9 Years ago, wed, march 25, 2015, 12:00:00

I know this has been asked before and I tried to do what was suggested but I can't seem to get it working.



Basically I've got links like this:



<ul>
<li class='current'><a href='portfolio/index.html'>portfolio</a></li>
<li><a href='about/index.html'>about</a></li>
</ul>


And then I've got a div like this:



<div class='loaded_content'></div>


What I want to do is, load the page in the link href into the div as I press the link. I also want to prevent the browser from navigating the link the normal way.



This is the script I have, which is loaded in the html header along with the jquery base:



$(document).ready(function() {
$('a').click(function(event){
event.preventDefault();
$('.loaded_content').load($(this).attr('href'));
return false;
});
});


What am I doing wrong?



edit:



Ok so I placed the script into the document.ready and the preventdefault is now working, but the href is still not getting loaded into the div.



edit:



Okay so I have got this working partially now. The html is now getting loaded properly into the div but I am now facing a new problem. The page I am loading is in a subdirectory along with its own .css file and some images. How can I make sure the css is being loaded aswell?



The reason I want to do this is because my pages on the website has the same structure on all pages, and I want to have like a frame website, where I only load the content of each page to keep from loading the same things over and over. Maybe there's another, better approach of this?


More From » jquery

 Answers
22

I think the problem is that the function isn't being called.



It can happen if you try to bind function to some elements when these elements are not yet in the document. You said that this code is the header, so, I think it is the case.



There are at least two options:



First: Write your javascript code inside a document.ready function:



$(document).ready(function(){
// your on click function here
$('a').click(function(){
$('.loaded_content').load($(this).attr('href'));
return false;
});
});


Second: Move your javascript code, writing it after the links.


[#67311] Monday, March 23, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mustafaericho

Total Points: 322
Total Questions: 103
Total Answers: 110

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
mustafaericho questions
Mon, May 31, 21, 00:00, 3 Years ago
Sun, May 23, 21, 00:00, 3 Years ago
Sat, Feb 13, 21, 00:00, 3 Years ago
Sat, Jan 2, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
;