I am making a question and answer page similar to Stackoverflow, though I am hand writing the code, basically for fun.
I am writing an ajax post that happens on click, which brings in a supposedly clickable div. The AJAX post looks something like this:
function answerQuestion(){
$('.answerQuestion').click(function(){
var user_id = $('#user_id').val();
var q_id = $('.q_id').val();
var answer = CKEDITOR.instances.editor1.getData();
if(answer && q_id && user_id){
$.post("scripts/questions/answerQuestion.php", {user_id : user_id, q_id : q_id, answer : answer}, function(answerThisQuestion) {
$('.answerTotalCont').last().css('border-bottom', '1px dashed #444');
$(answerThisQuestion).hide().appendTo('.allAnswers').slideDown(1000, 'easeOutExpo');
});
}
});
}
When the post appends the data, it brings in a clickable div called “answerAskButton”. This div has the possiblity of being on the page already when you load, and will always load after the AJAX call.
This ‘button’, when clicked makes a different AJAX post, basically for comments. Here is the code for it:
function submitComment(noType) {
//$('.answerAskButton').click(function(){
$('.answerAskButton').live("click", function(){
//GET ALL OF THE VARIABLES - THIS CODE IS FUNCTIONING PROPERLY - THIS IS JUST ABRIDGED TO SHOW SMALLER CODE
$.post("scripts/questions/postComment.php", {details : details, user_id : user_id, q_id : q_id, qora : qora, a_id : a_id}, function(postComment) {
noComment.slideUp(1000, 'easeOutExpo');
$(postComment).hide().appendTo(newComment).slideDown(1000, 'easeOutExpo');
$('.questComment').val(noType);
});
$('.questCommentsCont').slideUp(300, 'easeOutCirc');
$('.questComment').val(noType);
});
}
And these are both called on document load.
The problem is: When I make the answerQuestion() post, after it loads the AJAX data and shows a new clickable button, That button (answerAskButton) is no longer clickable, though, the other buttons that were obviously onload are still working.
I heard .live() was the way to fix this, but as you can see, it is not working for me.
any Advice?
UPDATE::
I have updated the code .on() instead of .live(), though it is still not working. If you would like to take a look at my code, the Login is here (username: public, password: public) and the page in question are any of these Question Pages which you can find on the Q&A page.
The script we’re talking about is called questions.js which is viewable through firebug or element inspector
As you’re using jQuery 1.7.x then instead of
live()use.on()like:Because
live()has been deprecated.Note
Syntax of
.on()for delegate event:Here,
containerpoints to aStatic-elementthat belong to DOM at page load.Full code
Tip
It would be better to use some other Static-element instead of
documentfor.on()delegation.