So I have this long function in jquery that includes a jquery ajax call, some css changes, and repositioning the div. Here is my code:
$('.editable').click(function(e) {
//assign the attributes for the ajax call
$('#employeelist span').html("job: " + $(this).attr("editjob") + "<br />date: " + $(this).attr("editdate").substr(5));
$('#employeelist').attr("editjob", $(this).attr("editjob"));
$('#employeelist').attr("editdate", $(this).attr("editdate"));
//update the employee list with AJAX
$.get("getDaySchedule.php",
{'job': $('#employeelist').attr("editjob"), 'date': $('#employeelist').attr("editdate")},
function(responsetext){$('#employeelist ul').html(responsetext);},
"html"
);
//show the employee list
$('#employeelist').show()
.css('top',$(this).offset().top+25)
.css('left',($(this).offset().left+130))
.css('visibility', "visible")
.removeClass()
.addClass($(this).attr('class'));
//adjust the employee list if it goes outside the viewable area:
if ($('#employeelist').height() + $('#employeelist').offset().top > $(window).height()) {
newtop = ($('#employeelist').height() + $('#employeelist').offset().top) - $(window).height();
newtop = $('#employeelist').offset().top - newtop;
$('#employeelist').css('top',newtop);
};
if ($('#employeelist').width() + $('#employeelist').offset().left > $(window).width()) {
newleft = $('#employeelist').offset().left - 260;
$('#employeelist').css('left',newleft);
};
});
The problem I’m having is that it appears the last section of code (where it repositions the div if it is outside the viewable area) is being run BEFORE the ajax call is done. So basically the height of the div is very short because it hasn’t gotten the response text yet. This results in the div being too tall and going past the viewable area, because it isn’t being repositioned off the correct height. Hopefully that makes sense. Is there something I’m missing in the code? Thanks!
Ajax by default is asynchronous, meaning that once it is called the following code will run without waiting for the ajax call to return; therefore, it is not complete when your following code runs. You need to move your code within the success of the ajax.
Edit:
I have updated the code to fix the issue you were having. Note I also cached the most commonly used jquery selectors. It is always a good idea to cache the selectors that you more than once to improve the performance of your code.