Reputation: 626
I have a function that uses ajax to load content throughout one of my sites.
This works all good but at some parts because new content is brought in that has more links I need to make the click function a live click function, but when I do the ajax stops working and it just changes the page as normal ( without ajax )
here is my code
function ajaxLoads(){
var $btn = $('a.ajax-btn');
var $container = $('#load');
var siteTitle = document.title;
//var $artistBG = $('#artist-viewport img');
$btn.click(function(e){
console.log();
e.preventDefault();
$btn.removeClass('selected');
//$artistBG.removeClass('top');
var sourceTarget = $(this).data('page'),
slideWidth = $container.width(),
$this = $(this),
$background = $this.data('background'),
pageUrl=$this.attr('href'),
pageTitle = $this.html();
//$changeTo = $("#artist-viewport img[data-background='"+ $background +"']");
$this.addClass('selected');
//$changeTo.addClass('top');
$container.animate({'right':-slideWidth}, 300, 'easeInExpo');
$container.load(pageUrl+" "+sourceTarget, function(){
subNav();
$("html, body").animate({ scrollTop: 0 }, 500, 'easeInExpo', function(){
$container.animate({'right':0}, 300, 'easeInExpo');
});
var pageContent = $(this).html();
window.history.pushState({"html":pageContent, "pageTitle": pageTitle},"", pageUrl);
//document.title=pageTitle+" :: "+siteTitle;
}); // end load function
}); // end click function
window.onpopstate = function(e){
if(e.state){
$container.css('opacity', 0).html(e.state.html).fadeTo('fast', 1);
document.title=e.state.pageTitle+" :: "+siteTitle;
}
};
}
I have tried changing the $btn.click(function(e) to $btn.live('click', function(e) and to $btn.on('click', function(e)
Upvotes: 1
Views: 261
Reputation: 1748
Give your button a css class and use this
$(document).on("click",".yourcssclass",function(e){});
This will work since by default, most events bubble up from the original event target to the document element.Though this degrades performance, a click event happens infrequently and you might use this as a fix to your problem.Then when you have time ,try to see why using delegates is not working by carefully looking on your page cycle.
Upvotes: 1
Reputation: 27364
Add .on
on document.
$(document).on('click','a.ajax-btn',function(){ });
Upvotes: 2