I have the following jquery script:
$(function(){
$('#top-menu').on('click', 'a.change-menu', function(e){
e.preventDefault()
$("#menu-change-div").load($(this).attr("href"));
});
});
$(function(){
$('#menu-change-div').on('click', 'a.change-content', function(e){
e.preventDefault()
$("#content").load($(this).attr("href"));
});
});
Here’s the HTML inside the body:
<div id="menu-div">
<div id="top-menu">
<h3 id="top-tabs"><a href="contentColumn.html" class="change-menu">Contents</a></h3>
<h3 id="top-tabs"><a href="indexColumn.html" class="change-menu">Index</a></h3>
<h3 id="top-tabs"><a href="searchColumn.html" class="change-menu">Search</a></h3>
</div>
<div id="menu-change-div">
<ul>
//Lots of nested list items and ul's with #change-content id
</ul>
</div>
</div>
<div id="content">
<div id = "page-content">
//content section
</div>
</div>
The first function occurs when I click a list item in my menu div and loads an html file into my content div.
The second one changes whats in my menu div when a different tab is selected.
I can click list item and everything works as expected and when I click the tabs it also works properly. My problem is occuring if I first click a list item, then click a tab, then click another list item. Instead of just loading the html into the div like it did on the first click, it instead just follows the href and opens it in another window. Any ideas what I’m doing wrong?
Try:
if elements are being added dynamically, then you need to change the way you’re using .on().
Per the docs:
Also note that you can combine your two
$(function () {...})into one.