I’ll try and explain what I’m trying to do as clearly as I can and hopefully people’ll be able to understand the issue.
$(document).ready(function() {
$('body').on('click', '.mainNav', function() {
var href = $(this).attr('href');
$('body').load(href);
});
});
This is the bit of code which has been causing me trouble. Basically what it’s -supposed- to do is grab the ‘href’ attribute from a div and then load that to replace the current content of the body tag.
This works the first time but when the new content is generated via .load() the div stops responding. I’m pretty new to JS so I apologize in advance if the answer is something obvious. I’ve been trying to find a solution on my own but everything I find tells me that .on() should work for dynamically generated content.
EDIT: Can’t emulate the problem in a fiddle so I’m posting a pastebin with the entire index page in hopes of it clarifying the problem.
EDIT: It works using adeneo’s solution. Much obliged to everyone for their input and apologies for not posting the entire thing from the start. I’m guessing it would’ve saved everyone some time.
Not really sure what the issue it, but I’m guessing it has something to do with loading into the same element as the handler is attached to, so try :
Also, you are of course aware that this will replace ALL content on your page, and unless there is a new element with the same class in the loaded content, nothing will happen. I would suggest using a container for loading the content into aswell. And of course, the links has to be to actual files on your server.
Also make sure the files you load does not have another set of
<head>,<body>tags etc. as that will mess things up for you, HTML content only!EDIT:
If
.mainNavis a<a href="link_you_are_trying_to_load"></a>type of element, you will have to prevent the default action as well, see updated code.NEW EDIT:
The problem you are having is pretty obvious, you are using elements like :
a div element has no attribute href, so JS will not get that value as it’s not a valid attribute for anything other than a
<a>elementYou can either change your element to an
<a>element or change the href attribute to:and do:
at least that would be valid HTML!
Also, you seem to have a “container” like element called
#siteso why don’t you do :