Skip to content
Advertisement

console displays Uncaught SyntaxError: Unexpected identifier

I modified the function moveElement and changed its formal parameter from elementID to element. I want to directly pass the DOM object from the function positionMessage to the function moveElement. Chrome keeps displaying an Uncaught Syntax error, and I have no idea where went wrong. I would appreciate it if you can give me some help or pointers.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</script>
    <script type="text/javascript" src="scripts/positionMessage.js"></script>
    <script type="text/javascript" src="scripts/moveElement.js"></script>
</head>
<body>
    <p id="message">Whee!</p>
</body>
</html>

moveElement.js:

function moveElement(element,finx,finy,interval){
    var xpos = parseInt(element.style.left); 
    var ypos = parseInt(element.style.top);
    if(xpos == finx && ypos == finy) return true;
    if(xpos > finx) xpos--;
    if(xpos < finx) xpos++;
    if(ypos > finy) ypos--;
    if(ypos < finy) ypos++;
    element.style.left = xpos+"px";
    element.style.top = ypos+"px";
    var repeat = "moveElement("+element+","+finx+","+finy+","+interval+")";
    var movement = setTimeout(repeat,interval);
}

positionMessage.js:

window.onload = positionMessage;
function positionMessage(){
    var elem = document.getElementById("message");
    elem.style.position = "absolute";
    elem.style.left = "50px";
    elem.style.top = "100px";
    moveElement(elem,200,100,10);
}

console display this error:

Uncaught SyntaxError: Unexpected identifier

Advertisement

Answer

So I think the issue comme from using the eval from setTimeout instead of creating a function

function moveElement(element,finx,finy,interval){
    var xpos = parseInt(element.style.left); 
    var ypos = parseInt(element.style.top);
    if(xpos == finx && ypos == finy) return true;
    if(xpos > finx) xpos--;
    if(xpos < finx) xpos++;
    if(ypos > finy) ypos--;
    if(ypos < finy) ypos++;
    element.style.left = xpos+"px";
    element.style.top = ypos+"px";
    var movement = setTimeout(function () {
        moveElement(element, finx, finy, interval);
    }, interval);

}

But you can also pass additionnal arguments to setTimeout that will be passed to your function.

function moveElement(element,finx,finy,interval){
    var xpos = parseInt(element.style.left); 
    var ypos = parseInt(element.style.top);
    if(xpos == finx && ypos == finy) return true;
    if(xpos > finx) xpos--;
    if(xpos < finx) xpos++;
    if(ypos > finy) ypos--;
    if(ypos < finy) ypos++;
    element.style.left = xpos+"px";
    element.style.top = ypos+"px";
    var movement = setTimeout(moveElement, interval, element, finx, finy, interval);
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement