Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm trying to make a simple little program in Node to use as a code base from with to program my whole web app. However, it isn't exactly working as planned because I'm stuck.

I wanted it so that when I move a red div around the screen, the position of the div moves on another page looking on with websockets, and both can do the same thing. So I made these two pages the same one for simplicity, utilizing "window.location.host" so that my index.js can talk to itself. However, it just isn't working! Please help.

<head>
    <meta charset="utf-8">
    <title>Simple Square Move</title>
    <style>
        textarea {
            padding: 5px 5px 5px 5px;
        }
        #alive {
            color:#999;
        }
        #element {
            cursor: move;
            position: absolute;
            top: 50px;
            left: 50px;
            background: red;
            height:50px;
            width:50px;
        }
    </style>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js"></script>
    <script>
        var ws = new WebSocket('ws://' + window.location.host);
        ws.onmessage = function (event) {

            // variable declarations

            var el = document.getElementById("element");
            var al = document.getElementById("alive");


            if (typeof event.data !== 'object') {
                var dataObj = JSON.parse(event.data);
                if (dataObj.square.type === "left") {
                   el.style.top = dataObj.square.message;
                } else if (dataObj.square.type === "top") {
                    el.style.top = dataObj.square.message;
                } else if (dataObj.square.type === "info") {
                al.innerHTML = 'Connected';
            }
        }
        };

var sendleft = function(ev) {
var position1 = {
    "square": {
        "type": "left",
        "message": ev.value
    }
};
ws.send(JSON.stringify(position1));
};

var sendtop = function(ev) {
var position2 = {
    "square": {
        "type": "top",
        "message": ev.value
    }
};
ws.send(JSON.stringify(position2));
};​
    </script>
    <script>
        $(document).ready(function () {

            $("#element").draggable().mousemove(function () {

                var coord = $(this).position();

                sendleft(coord.left);
                sendtop(coord.top);
            });
        });
    </script>
</head>

<body>
    <div id="alive"></div>
    <div id="element"></div>
</body>

</html>

I used https://github.com/trygve-lie/demos-html5-realtime as my server for Node.

Thank you very much!

share|improve this question
3  
This belongs on StackOverflow – David Barker Jul 5 '12 at 19:49

closed as off topic by ANeves, palacsint, Jeff Vanzella, Brian Reichle, codesparkle Oct 30 '12 at 21:03

Questions on Code Review Stack Exchange are expected to relate to code review request within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer

window.location.host returns a OS file path when ran from your local.

Your webpage can't communicate with the server because you're using the wrong url for the WebSocket.

Old Code:

var ws = new WebSocket('ws://' + window.location.host);

New Code:

var ws = new WebSocket('ws://localhost:9998');

The Socket, ws, in the new code connects to your server at localhost through port 9998.

Make sure to setup node.js and start your websocket server.

Install node ws to enable WebSockets in node.js.

Install node ws

npm install ws

Sample Server Code (filename: wsServerDemo.js):

var WebSocketServer = require('ws').Server, 
    wss = new WebSocketServer({port: 9998});

wss.on('connection', function(ws) {
    ws.on('message', function(message) {
        console.log('received: %s', message);
    });
    ws.on("open", function(){
        console.log( "open: connection" );
        console.dir( arguments );
    });
    ws.on('close',function(){
        console.log( "The connection is closed." );
        console.dir(arguments);
    });  
});

Start your websocket server.

node wsServerDemo.js

Client Side WebSocket HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple Square Move</title>
<style>
#alive {
    color:#999;
}
#element {
    cursor: move;
    position: absolute;
    top: 50px;
    left: 50px;
    background: red;
    height:50px;
    width:50px;
}
</style>
</head>
<body>
<div id="alive"></div>
<div id="element"></div>
import using script tag "http://code.jquery.com/jquery-1.7.1.min.js" 
import using script tag "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js"
import using script tag "main.js"

</body>
</html>

filename: main.js

var el = document.getElementById("element");
var al = document.getElementById("alive");
var ws = new WebSocket('ws://localhost:9998');

ws.onmessage = function (event) {
    console.log(event);    
    if (typeof event.data === 'string') {
        var dataObj = JSON.parse(event.data);
        if (!dataObj ){
            return;
        }
        $(el).css( dataObj.position );
    }
};
var sendPosition = function(pos){
    ws.send( JSON.stringify( {
        "position": JSON.stringify(pos)         
    }));
};
$(function () {
    $("#element").draggable().mousedown(function () {
        sendPosition( $(this).position() );
    });
});

Send out position on mousedown not on mousemove.

You should only care about the drop position of the box and not where it's moving to.

Old Code:

$("#element").draggable().mousemove(function () {
    sendPosition( $(this).position() );
});

New Code:

$("#element").draggable().mousedown(function () {
    sendPosition( $(this).position() );
});
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.