I have this really weird bug at my page. I wrote this comment system that when you add a comment it adds the new comment with a nice animation (unhides it by animating the height). Not the problem is, when you add a long comment (close to the max characters allowed) and after that add another one, the last animation stops when the height is 1px and all other animations on the page (like hovers) stop working as well. I have no idea what is causing this.
Here’s the link to my page http://ttrcustoms.us/testarea51/#track=1323924558
function addComment(el, evenorodd, user, avatar, comments){
numberofcomments = parseInt(comments);
newnumberofcomments = numberofcomments;
realnumberofcomments = numberofcomments + 1;
numberofcomments--;
theLastID = "#commentborder" + numberofcomments;
deleteLast = "#delete" + numberofcomments;
fadeLast = "#fade" + numberofcomments;
theCommentID = "#thecomment" + newnumberofcomments;
newcomment = "#fade" + newnumberofcomments;
commentID = "#comment" + newnumberofcomments;
commentBorderID = "#commentborder" + newnumberofcomments;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//Fade textarea
$("#enter-comment").attr("readonly", true).fadeTo(500, 0.5);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//Add the comment from the DB
document.getElementById("serverResponse").innerHTML=xmlhttp.responseText;
if(xmlhttp.responseText != "success"){
//Show error if there is one
jQuery.fn.center = function (widthmodification, heightmodification) {
this.css("position","fixed");
this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + heightmodification + "px");
this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + widthmodification + "px");
return this;
}
$("#serverResponse").center(-32, -75);
$("#pageoverlay").fadeTo(500, 0.75);
$("#serverResponse").fadeIn(500);
$("#pageoverlay").click(function() {
$("#serverResponse").fadeOut(500);
$("#pageoverlay").fadeOut(500);
$(deleteimg).html("✖");
$("#enter-comment").fadeTo(500, 1);
});
}else{
//Show the comment
$(fadeLast).after("\n<span id='fade"+newnumberofcomments+"' class='fadecomment' onmouseover='$(\"#delete"+newnumberofcomments+"\").fadeTo(200,1);' onmouseout='deleteOut(event, \""+newnumberofcomments+"\")' style='display: none; width: 679px;'>\n<span class='comment' id='comment"+newnumberofcomments+"'>\n<span class='"+evenorodd+" bottom-comment' id='commentborder"+newnumberofcomments+"'>\n<div class='avatarWrapper' id='avatarwrap"+newnumberofcomments+"'><img src='images/avatars/"+avatar+"' class='avatar32' id='avatar"+newnumberofcomments+"'/></div>\n<span class='thecomment' id='thecomment"+newnumberofcomments+"'>\n<a href='#' class='userl' id='userl"+newnumberofcomments+"'>"+user+"</a> "+el.elements['enter-comment'].value+"</span>\n</span>\n<span class='delete-holder' id='delete-holder"+newnumberofcomments+"'>\n<span class='delete-comment' style='opacity: 0;' id='delete"+newnumberofcomments+"' lang='bottom' onclick='removecomment(0,\"1\",this.lang,\"even\",document.getElementById(\"nrofcomments\").innerHTML);'>✖</span>\n</span>\n</span>\n</span>\n");
$(newcomment).css({visibility:"visible",display:"block",position:"absolute"});
theHeight = $(theCommentID).height() + 2;
if(theHeight < 36){
theHeight = 36;
}
$(newcomment).css({display:"none",position:"relative",visibility:"visible"});
$(commentID).height(theHeight);
$(commentBorderID).height(theHeight);
$(newcomment).height(theHeight);
$(newcomment).animate({height: 'show'},500);
$("html, body").animate({ scrollTop: $(document).height() }, 500);
//Flat out corners of last comment
$(theLastID).removeClass("bottom-comment").addClass("middle-comment");
$(deleteLast).attr("lang", "middle");
//Reset texarea
$("#enter-comment").fadeTo(500, 1).removeAttr("readonly").val("Write a comment...").css("color","#ccc");
//Change the current number of comments and if the next one needs to be even or odd
$("#nrofcomments").html(realnumberofcomments);
if(evenorodd == "even"){
$("#newevenorodd").html("odd");
}else{
$("#newevenorodd").html("even");
}
}
}
}
query = 'enter-comment=' + el.elements['enter-comment'].value;
xmlhttp.open("POST","spotlight/comment.php?add=true",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(query);
}
Okay. Hello, spaghetti-code! 😉
It’s hard to tell what exactly is going on, but one thing I noticed is this:
When typing a comment, the moment the comment becomes too long and the height of the text field is animated, the JS console starts spewing uncaught
RangeErrors (“Maximum call stack size exceeded”). So there’s something amiss there. And since you said the problem occurs after you add a long comment, I think it’s a safe bet this is what causing it.This error is usually indicative of an infinite loop. So look for that. Hint: you can use Firebug or Chrome WDT to inspect where in jQuery the RangeError occurs. It’s hard to tell because you’re using a minified version of jQuery, but my guess is that you’re using
$()to create new DOM elements (in a loop, as said).Now, I don’t think anyone here is going to take the (possibly huge amount of) time necessary to debug this code in its current form. Maybe you’ll get lucky and someone will spot the problem, but I wouldn’t count on it.
So, what else can you do? Well, now that you’ve experienced how to write spaghetti code, perhaps it’s time to go Object Oriented? Write your own types (or “classes”) so you can represent “objects” on a the page (e.g. a single comment, the comment list, the new comment field, etc.). These objects can keep references to the DOM nodes, as well as to the state of the “objects” they represent. Furthermore, they could have simple-to-call methods that wrap more complicated logic.
The main goal of this is code readability. Really? Yes, really. I could preach about avoid things like strong coupling between HTML and JS using
onclickandonmouseoverattributes (it’s bad, m’kay?), but that is not the real goal of having an object-oriented JavaScript architecture. When your application starts getting more complex, it’s harder to keep track of what does what to what and where. By bundling your code into distinct pieces, it’s easier to reason about what’s going on. Instead of 30 lines of low-level code, you could have one function call (e.g.newComment.animate('open'), or something like that).On top of that, creating objects for every “object” on the page allows you to make them responsible for their own behaviour, and nothing but their own behaviour. When you take this really seriously (and many do), you call it the single responsibility principle.
So I recommend you read about OO JavaScript. Leave jQuery out of it while you’re learning more about JavaScript itself. And then… start rewriting your application, bit by bit. Yes, it will take a lot of time. But it will be worth it, because your application will be much more maintainable.
Useful resources: