I am using jQuery 1.9.1 and have two scenarios where the same content can be loaded via an AJAX call. Since there are two scenarios, I am using class as the selector as opposed to ID since the ID will only work on the first instance.
Scenario one, in the menu, an href element with class="firstlink".
Scenario two, a customised autocomplete which outputs a link as the search term, again, this link has the class "firstlink". The autocomplete script is called in the of the document.
The following works clicking on the menu item class "firstlink" on first and subsequent loads/clicks on the page.
$(document).ready(function(){
$(".firstlink").click(function(){
$.ajax({url:"resources/pageone.html",dataType:"html",success:function(result){
$(".content-area").html(result);
}});
});
});
Because the autocomplete adds the second link with the class "firstlink" into the DOM, the above doesn't work for the dynamically generated link with this same class, so I must use 'on', which I am using like this:-
$(document).ready(function(){
$(document).on("click",".firstlink", function () {
$.ajax({url:"resources/pageone.html",dataType:"html",success:function(result){
$(".content-area").html(result);
}});
});
});
This works on the dynamically generated element with class "firstlink" but it does not work on the menu item with class "firstlink" which is in the DOM.
I have also tried in the same document ready function:-
$('.firstlink').on("click" ,function() {
$.ajax({url:"resources/pageone.html",dataType:"html",success:function(result){
$(".content-area").html(result);
}});
});
});
This works with the static (already existing in DOM) element with class "firstlink" but not with the dynamically created element of the same class name.
I am sure there must be a reason for this and that I do not require to define the same piece of code twice for the same function, as "$(".firstlink").click(function(){" and "$(document).on("click",".firstlink", function () {" produce the same outcome - the same AJAX content is loaded.
Sample HTML code:-
Static HTML:-
<ul>
<li><a href="#" class="firstlink">click here first</li>
<li><a href="#" class="secondlink">click here second</li>
<li><a href="#" class="thirdlink">click here third</li>
</ul>
The dynamically generated by autocomplete (jQuery) link is like this:-
<div class="search-output">
<a href="#" class="firstlink">please click here</a>
</div>
`