Web Analytics Made Easy -
StatCounter Rewrite of script - CodingForum

Announcement

Collapse
No announcement yet.

Rewrite of script

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Rewrite of script

    Hey, I have been working on http://somebots.com/voke/ for a little while now, and I think the next thing I should do is rewrite the javascript. The current js seems to be pretty inefficient. I don't really know js that well, and just kind of patched this together. Here's the current javascript page (main.js):
    Code:
    var KEYUP = 38;
    var KEYDOWN = 40;
    var KEYENTER = 13;
    var KEYTAB = 9;
    
    var xmlHttp;
    var suggestionsShown = false;
    var currentlySelectedLi = -1;
    
     var viewportwidth;
     var viewportheight;
     if (typeof window.innerWidth != 'undefined')
     {
          viewportwidth = window.innerWidth,
          viewportheight = window.innerHeight
     }
    
     else if (typeof document.documentElement != 'undefined'
         && typeof document.documentElement.clientWidth !=
         'undefined' && document.documentElement.clientWidth != 0)
     {
           viewportwidth = document.documentElement.clientWidth,
           viewportheight = document.documentElement.clientHeight
     }
    
     else
     {
           viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
           viewportheight = document.getElementsByTagName('body')[0].clientHeight
     }
    var boxwidth = parseInt(viewportwidth)*0.57;
    var boxwidth2 = parseInt(boxwidth)+6;
    window.onload=function(){
    document.getElementById('iText').style.width = boxwidth + 'px';
    document.getElementById('suggestions').style.width = boxwidth2 + 'px';
    document.getElementById('ul').style.width = boxwidth2 + 'px';
    document.getElementById('li').style.width = boxwidth2 + 'px';
    document.getElementById('hoverLi').style.width = boxwidth2 + 'px';
    }
    
    function deselectLi(list, li) {
        if(li != -1) {
            list[li].className = "li";
        }
    }
    
    function deselectText(iText, text, color) {
    	if (iText.value=="") {
    		iText.value = text;
    	}
    	iText.style.color = color;
    }
    
    function selectText(iText, text, color) {
    	if (iText.value==text) {
    		iText.value = "";
    	}
    	iText.style.color = color;
    }
    function deselectPass(iText, password, color) {
    	if (iText.value=="") {
    		iText.value = password;
    	}
    	iText.style.color = color;
    }
    
    function selectPass(iText, password, color) {
    	if (iText.value==password) {
    		iText.value = "";
    	}
    	iText.style.color = color;
    }
    
    function getList() {
    	
    	return document.getElementById("suggestions").getElementsByTagName("li");
    	
    }
    
    function getXmlHttpObject() {
    
    	var xmlHttp = null;
    	
    	try {
    		xmlHttp = new XMLHttpRequest();                           // Firefox, Opera 8.0+, Safari
    	}
    	catch (e) {
    		try {
    			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");        // Internet Explorer
    		}
    		catch (e) {
    			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");     // Internet Explorer
    		}
    	}
    	
    	return xmlHttp;
    	
    }
    
    function handleInput(e, userInput) {
    	var theEvent = e || window.event;
    
    	if (userInput.length == 0) {
    		emptySuggestions();
    		return;
    	}
    	
    	if (theEvent.keyCode == KEYUP || theEvent.keyCode == KEYDOWN) {
    	
    	    var list = getList();
    	    
    	    if(theEvent.keyCode == KEYDOWN) {
    	        var newSelectedLi = currentlySelectedLi + 1;
    	    }
    	    else {
    	        var newSelectedLi = currentlySelectedLi - 1;
    	    }
    	    
    	    if(newSelectedLi <= 9 && newSelectedLi >= 0) {
    	        selectLi(list, newSelectedLi, true);
    	        deselectLi(list, currentlySelectedLi);
    	        setCurrentLi(newSelectedLi);
    	    }
    	    
            return;
            
    	}
    	
    	xmlHttp = getXmlHttpObject();
    	
    	if (xmlHttp == null) {
    		alert("The internet browser you're currently using doesn't support voke. Please update to a newer version.");
    		return;
    	} 
    	
    	var url = "answer.php?query=" + userInput;
    	
    	xmlHttp.onreadystatechange = stateChanged
    	xmlHttp.open("GET", url, true);
    	xmlHttp.send(null);	
    }
    
    function handleTab(e) {
    	
    	var theEvent = e || window.event;
        
        if(theEvent.keyCode == KEYTAB && document.getElementById("suggestions").innerHTML != "") {
    		setInputText();
            emptySuggestions();
        }
        
    }
    
    function newCurrentLi(li) {
        var list = getList();
        
        for(var i = 0; i < list.length; i++) {
            if(i == li) {
                selectLi(list, li, false);
                setCurrentLi(li);
            }
            else {
                deselectLi(list, i);
            }
        }
    }
    
    function resetCurrentLi() {
        currentlySelectedLi = -1;
    }
    
    function selectLi(list, li, updateInputText) {
        list[li].className = "hoverLi";
        
        if (updateInputText) {
            setInputText(li);
        }
    }
    
    function setCurrentLi(li) {
        currentlySelectedLi = li;
    }
    
    function setInputText(li) {
    	
    	var list = getList();
    	
    	if(li >= 0) {
    		document.getElementById("inputText").value = list[li].innerHTML.substring(6);
    	}
    	else {
    		document.getElementById("inputText").value = list[currentlySelectedLi].innerHTML.substring(6);
    	}
      
    }
    function stateChanged() {
    	if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
    		suggestionsShown = true;
    		var split = xmlHttp.responseText.split("new2theline");
    		var suggestionList = "";
    		if(split[0] != "") {
    			for(var i = 0; i < split.length; i++) {
    				suggestionList += "<li value='" + i + "' class=\"li\" id=\"li\" onmouseover=\"newCurrentLi(this.value);\" onclick=\"handleClick('" + escape(split[i]) + "');\">" + split[i].substr(0, 1024) + "</li>";
    				document.getElementById("suggestions").innerHTML = suggestionList;
    			}
    			if(suggestionList != "") {
    				suggestionList = "<ul class=\"ul\" id=\"ul\">" + suggestionList;
    				suggestionList += "</ul>";
    				document.getElementById("suggestions").innerHTML = suggestionList;
    			}
    		    document.getElementById("suggestions").innerHTML = suggestionList;
    		    document.getElementById("suggestions").style.display = 'block';
    		} else {
    		    document.getElementById("suggestions").style.display = 'none';
    		}
    	}
    }
    If anyone could give me any hints as to what I can do to make this better or any code that's not required, that would be great. The only external calls to this are from the index and it's only handleInput().

    Also, tell me how you like the site and if you have any suggestions. Thanks!

  • #2
    The only thing I see at first glance is that you make a lot of "tests" reusing the same code over and over.

    Example:
    Code:
    function stateChanged() {
    	if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
    		suggestionsShown = true;
    		var split = xmlHttp.responseText.split("new2theline");
    		var suggestionList = "";
    		if(split[0] != "") {
    			for(var i = 0; i < split.length; i++) {
    				suggestionList += "<li value='" + i + "' class=\"li\" id=\"li\" onmouseover=\"newCurrentLi(this.value);\" onclick=\"handleClick('" + escape(split[i]) + "');\">" + split[i].substr(0, 1024) + "</li>";
    				[COLOR="Red"]document.getElementById("suggestions")[/COLOR].innerHTML = suggestionList;
    			}
    			if(suggestionList != "") {
    				suggestionList = "<ul class=\"ul\" id=\"ul\">" + suggestionList;
    				suggestionList += "</ul>";
    				[COLOR="Red"]document.getElementById("suggestions")[/COLOR].innerHTML = suggestionList;
    			}
    		    [COLOR="Red"]document.getElementById("suggestions")[/COLOR].innerHTML = suggestionList;
    		    [COLOR="Red"]document.getElementById("suggestions")[/COLOR].style.display = 'block';
    		} else {
    		    [COLOR="Red"]document.getElementById("suggestions")[/COLOR].style.display = 'none';
    		}
    	}
    }
    Why not get the reference to the element (or whatever) ONE TIME and then use it throughout?
    Code:
    function stateChanged() {
    	if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
                    [COLOR="Red"]var sugDiv = document.getElementById("suggestions");[/COLOR]
    		suggestionsShown = true;
    		var split = xmlHttp.responseText.split("new2theline");
    		var suggestionList = "";
    		if(split[0] != "") {
    			for(var i = 0; i < split.length; i++) {
    				suggestionList += "<li value='" + i + "' class=\"li\" id=\"li\" onmouseover=\"newCurrentLi(this.value);\" onclick=\"handleClick('" + escape(split[i]) + "');\">" + split[i].substr(0, 1024) + "</li>";
    				[COLOR="Red"]sugDiv[/COLOR].innerHTML = suggestionList;
    			}
    			if(suggestionList != "") {
    				suggestionList = "<ul class=\"ul\" id=\"ul\">" + suggestionList;
    				suggestionList += "</ul>";
    				[COLOR="Red"]sugDiv[/COLOR].innerHTML = suggestionList;
    			}
    		    [COLOR="Red"]sugDiv[/COLOR].innerHTML = suggestionList;
    		    [COLOR="Red"]sugDiv[/COLOR].style.display = 'block';
    		} else {
    		    [COLOR="Red"]sugDiv[/COLOR].style.display = 'none';
    		}
    	}
    }
    But will that even be noticeable, performance wise? Nah.

    But maybe other places--e.g., in loops--see if you have redundant code like that.
    Be yourself. No one else is as qualified.

    Comment


    • #3
      Ok, thanks, I'll do that.

      Does anyone have any others?

      Comment


      • #4
        i think u should focus on getting it working before trying to improve your coding techniques.

        i typed in a few words on http://somebots.com/voke/ and got this error:
        Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL resource in
        /Volumes/Data/Web/vhost/somebots.com/voke/answer.php on line 65

        Warning: mysql_free_result(): supplied argument is not a valid MySQL resource in
        /Volumes/Data/Web/vhost/somebots.com/voke/answer.php on line 70

        Comment


        • #5
          Originally posted by Osman View Post
          i think u should focus on getting it working before trying to improve your coding techniques.

          i typed in a few words on http://somebots.com/voke/ and got this error:
          Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL resource in
          /Volumes/Data/Web/vhost/somebots.com/voke/answer.php on line 65

          Warning: mysql_free_result(): supplied argument is not a valid MySQL resource in
          /Volumes/Data/Web/vhost/somebots.com/voke/answer.php on line 70
          I know it's not working now, working on the PHP. Should be up later tomorrow.

          Comment


          • #6
            Ok, it's working.

            Any more suggestions for the JS?

            Comment

            Working...
            X