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!