Strange behaviour of included JS file in node.js - javascript

I am making a node app that is in it current state very simple, but I get an issue I can't figure out.
The generated html of my express app looks like this:
<html style="" class=" js no-touch svg inlinesvg svgclippaths no-ie8compat">
<head>
...
<script type="text/javascript" src="/javascripts/mouse.js"></script>
...
</head>
<body class="antialiased" style=""><div class="row"><div class="row">
<script>
var mouse;
var X = 0;
var Y = 0;
window.onload = function()
{
alert(Mouse());//=> undefined
mouse = Mouse();
mouse.setMouseMoveCallback(function(e){ //THIS LINE FAILS: "Cannot call method 'setMouseMoveCallback' of undefined"
X = e.x;
Y = e.y;
alert("move");
});
}
...
</html>
The include script tag in the header adds this javascript file:
function Mouse(onObject){
var mouseDown = [0, 0, 0, 0, 0, 0, 0, 0, 0],
mouseDownCount = 0;
var mouseDownCallbacks = [0, 0, 0, 0, 0, 0, 0, 0, 0];
var mouseTracer = 0;
var tracePosArray;
var target = onObject;
if(!onObject){
onObject = document;
}
onObject.onmousedown = function(evt) {
mouseDown[evt.button] = 1;
mouseDownCount--;
if(mouseDownCallbacks[evt.button] != 0){
mouseDownCallbacks[evt.button](evt);
}
}
onObject.onmouseup = function(evt) {
mouseDown[evt.button] = 0;
mouseDownCount--;
}
var mousemoveCallback;
onObject.onmousemove = function(evt){
//Tracing mouse here:
if(mouseTracer){
tracePosArray.push([evt.pageX,evt.pageY]);
}
if(mousemoveCallback){
mousemoveCallback(evt);
}
}
var mouseWheelCallback;
onObject.onmousewheel = function(evt){
if(mouseWheelCallback){
mouseWheelCallback(evt);
}
}
var mouseOverCallback;
onObject.onmouseover = function(evt){
if(mouseOverCallback){
mouseOverCallback(evt);
}
}
var mouseOutCallback;
onObject.onmouseout = function(evt){
if(mouseOutCallback){
mouseOutCallback(evt);
}
}
//TODO: There is a bug when you move the mouse out while you are pressing a button. The key is still counted as "pressed" even though you release it outside of the intended area
//NOTE: might have fixed the bug. Do some further investigation by making a smaller element.
this.anyDown = function(){
if(mouseDownCount){
for(p in mouseDown){
if(mouseDown[p]){
return true;
}
}
}
}
this.setLeftDownCallbackFunction = function(fun){
mouseDownCallbacks[0] = fun;
}
this.setRightDownCallbackFunction = function(fun){
mouseDownCallbacks[2] = fun;
}
this.setMiddleDownCallbackFunction = function(fun){
mouseDownCallbacks[4] = fun;
}
this.setSpcifiedDownCallbackFunction = function(num, fun){
mouseDownCallbacks[num] = fun;
}
this.leftDown = function(){
if(mouseDownCount){
return mouseDown[0] != 0;
}
}
this.rightDown = function(){
if(mouseDownCount){
return mouseDown[2] != 0;
}
}
this.middleDown = function(){
if(mouseDownCount){
return mouseDown[4] != 0;
}
}
this.setMouseMoveCallback = function (callback){
mousemoveCallback = callback;
}
this.setMouseWheelCallback = function (callback){
mouseWheelCallback = callback;
}
this.setMouseOverCallback = function (callback){
mouseOverCallback = callback;
}
this.setMouseOutCallback = function (callback){
mouseOutCallback = callback;
}
this.enableTracer = function(){
tracePosArray = new Array();
mouseTracer = 1;
}
this.getMouseTracerData = function() {
return tracePosArray;
}
}
So: I have assured that the JS file is loaded. But none the less I am not able to access the Mouse() method in my window.onload function in the body, it shows up as undefined. This is very strange to me because if I create a HTML file that does exactly the same thing I am able to access it.
What is going on here? Is there some magic trickery in node.js / express that disables this kind of interaction?
Additional notes:
I am using Jade as the template engine.
The "mouse.js" file works. I have used it several times before.
I am using socket.io for communication between the client and server.
Complete header:
<head><title>My awesome title</title><link rel="stylesheet" href="/stylesheets/foundation.min.css"><link rel="stylesheet" href="/stylesheets/normalize.css"><link rel="stylesheet" href="/stylesheets/style.css"><script type="text/javascript" src="/socket.io/socket.io.js"></script><style type="text/css"></style><script type="text/javascript" src="/javascripts/jquery.min.js"></script><script type="text/javascript" src="/javascripts/vendor/custom.modernizr.js"></script><script type="text/javascript" src="/javascripts/vendor/zepto.js"></script><script type="text/javascript" src="/javascripts/mouse.js"></script><meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"><meta name="viewport" content="width=device-width"></head>

That would throw an error if the Mouse function is undefined. The reason alert shows 'undefined' is that the Mouse function doesn't return anything, hence undefined. It should be used as a constructor, as in 'new Mouse()'

Related

p5js is adding div each time when click

#Hey-PeePs. The issue is happening in p5js:
I have: 1 function(), 1 draw(), 2 sketches(canvas)
Using: Instance Mode
All I want is a gallery! there is an image in thumbnail size, when click goes full-size, which is the reason I have 2 canvases. The following code is working. It will create a canvas with the thumbnail size of the image and then when I click on it, it will create a DIV which contains the full-screen image.
The issue is, every time I click on the thumbnail, it will create another DIV and it just goes on. How can I set a condition for this? So it will only draw once!
var PictureThumbnail = function(p) {
let ThumbImage;
let fullSize;
p.preload = function() {
ThumbImage = p.loadImage('https://www.paulwheeler.us/files/Coin120.png');
};
p.setup = function() {
var canvas = p.createCanvas(100, 100);
canvas.parent('#Thumbnail');
fullSize = createDiv('Full Size Image');
fullSize.addClass('fullSize');
fullSize.hide();
};
p.draw = function() {
p.image(ThumbImage, 0, 0, 700, 70);
if (mouseIsPressed) {
if ((p.mouseX > 0) && (p.mouseX < 100) && (p.mouseY > 0) && (p.mouseY < 100)) {
fullSize.show();
let sketch2 = function(p) {
p.setup = function() {
p.createCanvas(500, 500);
p.background(255);
}
};
new p5(sketch2, window.document.getElementById('fullSize'));
}
}
};
};
let sketch = new p5(PictureThumbnail);
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
</head>
<body>
<div id="Thumbnail"></div>
</body>
</html>
The last line of code is the issue.
new p5(sketch2, window.document.getElementById('fullSize'));
There are a number of issues:
1. Invalid references:
You have several references to global p5.js methods and properties where you should be referencing the instance methods (createDiv and mouseIsPressed).
2. Action in draw() that should be in mousePressed()
The way you're using mouseIsPressed is flawed. Draw is going to be running repeatedly and mouseIsPressed will be true over several calls so you're going to be repeatedly creating sketch2.
3. Attempt to get an element by id that does not exist
You create a div with the class 'fullSize' and no id and then you attempt to get an element with the id 'fullSize' but no such element exist.
Here's a working example:
var PictureThumbnail = function(p) {
let ThumbImage;
let fullSize;
let fullSizeOpen = false;
p.preload = function() {
ThumbImage = p.loadImage('https://www.paulwheeler.us/files/Coin120.png');
};
p.setup = function() {
var canvas = p.createCanvas(100, 100);
canvas.parent('#Thumbnail');
fullSize = p.createDiv('Full Size Image');
fullSize.addClass('fullSize');
fullSize.id('fullSize');
fullSize.hide();
};
p.mousePressed = function() {
if ((p.mouseX > 0) && (p.mouseX < 100) && (p.mouseY > 0) && (p.mouseY < 100)) {
if (!fullSizeOpen) {
fullSizeOpen = true;
fullSize.show();
let sketch2 = function(p) {
p.setup = function() {
p.createCanvas(500, 500);
p.background('red');
}
};
new p5(sketch2, window.document.getElementById('fullSize'));
}
}
}
p.draw = function() {
p.image(ThumbImage, 0, 0, 700, 70);
};
};
let sketch = new p5(PictureThumbnail);
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
</head>
<body>
<div id="Thumbnail"></div>
</body>
</html>

Difficulty implementing handleOnPress function

I am trying to implement the handleOnPress function, the code is provided by the textbook which is confusing because it doesn't seem to be working as expected, in fact it does nothing.
The function is supposed to allow me to click the squares in the memory game, if the squares are the same color both of the chosen squares disappear, if you click on the same square twice the function resets and if you match two that aren't the same the function resets.
It would be really appreciated if anyone can take a look and point out any errors they see, thank you!
<!DOCTYPE html>
<html>
<head>
<title>Recipe: Drawing a square</title>
<script src="easel.js"></script>
<script type="text/javascript">
var canvas;
var stage;
var squareSide = 70;
var squareOutline = 5;
var max_rgb_color_number = 255;
var gray = createjs.Graphics.getRGB(20, 20, 20);
var placementArray = [];
var highlight = createjs.Graphics.getRGB(255, 255, 0);
var tileClicked;
function init() {
var rows = 6;
var columns = 6;
var squarePadding = 10;
canvas = document.getElementById('myCanvas');
stage = new createjs.Stage(canvas);
var numberOfTiles = rows*columns;
setPlacementArray(numberOfTiles);
for(var i=0;i<numberOfTiles;i++){
var placement = getRandomPlacement(placementArray);
if(i % 2 === 0){
var color = randomColor();
}
square = drawSquare(color);
square.color = color;
square.x = (squareSide+squarePadding) * (placement%columns);
square.y = (squareSide+squarePadding) * Math.floor(placement/columns);
stage.addChild(square);
square.onPress = handleOnPress;
stage.update();
}
}
function drawSquare(color) {
var shape = new createjs.Shape();
var graphics = shape.graphics;
graphics.setStrokeStyle(squareOutline);
graphics.beginStroke(gray);
graphics.beginFill(color);
graphics.rect(squareOutline, squareOutline, squareSide, squareSide);
return shape;
}
function randomColor(){
var color = Math.floor(Math.random()*max_rgb_color_number);
var color2 = Math.floor(Math.random()*max_rgb_color_number);
var color3 = Math.floor(Math.random()*max_rgb_color_number);
return createjs.Graphics.getRGB(color, color2, color3);
}
function setPlacementArray(numberOfTiles){
for(var i=0;i<numberOfTiles;i++){
placementArray.push(i);
}
}
function getRandomPlacement(placementArray){
randomNumber = Math.floor(Math.random()*placementArray.length);
return placementArray.splice(randomNumber, 1)[0];
}
function handleOnPress(event){
var tile = event.target;
if(!!tileClicked === false){
tile.graphics.setStrokeStyle(squareOutline).beginStroke(highlight)
.rect(squareOutline, squareOutline, squareSide, squareSide);
tileClicked = tile;
}
else{
if(tileClicked.color === tile.color && tileClicked !== tile){
tileClicked.visible = false;
tile.visible = false;
}
else{
tileClicked.graphics.setStrokeStyle(squareOutline).beginStroke(gray)
.rect(squareOutline, squareOutline, squareSide, squareSide);
}
tileClicked = null;
}
stage.update();
}
</script>
</head>
<body onload="init()">
<canvas id="myCanvas" width="960" height="600"></canvas>
</body>
</html>
The onEvent-style handlers (onClick, onMouseDown, etc) were deprecated and removed a long time ago (Version 0.7.0, September 25, 2013).
Instead, use events, such as
square.addEventListener("mousedown", handleOnPress);
or the shortcut on() method:
square.on("mousedown", handleOnPress);
Note also there is no "press" event. There is a "mousedown" event, as well as "pressmove"/"pressup" events for drag and drop-style events.
Here is a listing of events on all display objects: https://createjs.com/docs/easeljs/classes/DisplayObject.html#event_mousedown
I don't know if this will solve everything, but it should get your click handlers firing.

Pixi.js touch events not firing on iPhone after pushing intel-xdk files

I have created a small test project to replicate the problem.
The project contains only pixi.min.js and index.html with code from this example:
http://pixijs.github.io/examples/index.html?s=demos&f=interactivity.js&title=Interactivity
Buttons work when I test it via the browser.
They also work in the intel-xdk emulate tab.
But when I go to test tab, push files, scan QR code to open the created app on the iphone, the buttons appear but touch events are not working.
Why are the touch events not firing on the iPhone?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body style="margin:0; padding: 0; background: #333333;">
<script src="pixi.min.js"></script>
<script>
var renderer = PIXI.autoDetectRenderer(800, 600);
document.body.appendChild(renderer.view);
var stage = new PIXI.Container();
var textureButton = PIXI.Texture.fromImage('images/button.png');
var textureButtonDown = PIXI.Texture.fromImage('images/button.png');
var textureButtonOver = PIXI.Texture.fromImage('images/button2.png');
var buttons = [];
var buttonPositions = [
175, 75,
655, 75,
410, 325,
150, 465,
685, 445
];
var noop = function () {
//console.log('click');
};
for (var i = 0; i < 5; i++)
{
var button = new PIXI.Sprite(textureButton);
button.buttonMode = true;
button.anchor.set(0.5);
button.position.x = buttonPositions[i*2];
button.position.y = buttonPositions[i*2 + 1];
button.interactive = true;
button.on('mousedown', onButtonDown)
.on('touchstart', onButtonDown)
.on('mouseup', onButtonUp)
.on('touchend', onButtonUp)
.on('mouseupoutside', onButtonUp)
.on('touchendoutside', onButtonUp)
.on('mouseover', onButtonOver)
.on('mouseout', onButtonOut);
button.tap = noop;
button.click = noop;
stage.addChild(button);
buttons.push(button);
}
buttons[0].scale.set(1.2);
buttons[2].rotation = Math.PI / 10;
buttons[3].scale.set(0.8);
buttons[4].scale.set(0.8,1.2);
buttons[4].rotation = Math.PI;
animate();
function animate() {
renderer.render(stage);
requestAnimationFrame(animate);
}
function onButtonDown(){
this.isdown = true;
this.texture = textureButtonDown;
this.alpha = 1;
}
function onButtonUp(){
this.isdown = false;
if (this.isOver){ this.texture = textureButtonOver;
}else{ this.texture = textureButton; }
}
function onButtonOver(){
this.isOver = true;
if (this.isdown){
return;
}
this.texture = textureButtonOver;
}
function onButtonOut(){
this.isOver = false;
if (this.isdown){ return; }
this.texture = textureButton;
}
</script>
</body>
</html>
var textureButton = PIXI.Texture.fromImage('images/button.png');
var textureButtonDown = PIXI.Texture.fromImage('images/button.png');
var textureButtonOver = PIXI.Texture.fromImage('images/button2.png');
It is working on iPhone, but you are not seeing anything happen cause you have the initial button image textureButton and textureButtonDown same (button.png). So you are not seeing any difference on screen when u touch on it. On iPhone there is no hover event for touch event, so the textureButtonOver is not applied
But when u test on emulator, you are using mouse, so when u move the mouse over the button textureButtonOver is applied and u see a change on screen.
So change the textureButtonDown to a different image (button3.png) and u will see it work on iPhone

Function with if-else doesn't work properly

I made a function which should disable a button if a variable isn't greater than or equal to another one. This function is run every second on a setInterval(), and the first variable to compare is also incremented by one on the setInterval(). But, the function (evitarNegs()), isn't working properly, and the button is always disabled. Sorry that part of the code is in spanish.
Javascript:
var GmB = {cantidad: 0, perSec: 1};
function Upgrade (pb, ps) {
this.precioBase = pb;
this.perSec = ps;
this.cantidad = 0;
this.precio = pb;
}
Upgrade.prototype.comprar = function() {
GmB.cantidad = GmB.cantidad - this.precio;
GmB.perSec = GmB.perSec + this.perSec;
this.cantidad++;
document.getElementById("gmb").innerHTML = GmB.cantidad;
this.precio = Math.ceil(this.precioBase*Math.pow(1.15, this.cantidad));
evitarNegs();
};
function loop() {
GmB.cantidad = GmB.cantidad + GmB.perSec;
document.getElementById("gmb").innerHTML = GmB.cantidad;
evitarNegs();
}
var upg = new Upgrade(10, 1);
var boton1 = document.getElementById("boton1");
boton1.disabled = true;
window.setInterval(loop, 1000);
//Problematic function
function evitarNegs() {
if (!(GmB >= upg.precio)) {
boton1.disabled = true;
}else {
boton1.disabled = false;
}
}
boton1.onclick = function() {
upg.comprar();
};
HTML:
<html>
<head>
<title>Gummy Bears</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<p id="gmb">0</p>
<button id="boton1" type="button">Upgrade 1</button>
<script src="main.js"></script>
</body>
</html>
You are comparing GmB to upg.precio, but GmB is an object. So you want
function evitarNegs() {
if (!(GmB.cantidad >= upg.precio)) {
boton1.disabled = true;
} else {
boton1.disabled = false;
}
}
However, this can be written much easier as
function evitarNegs() {
boton1.disabled = GmB.cantidad < upg.precio;
}
Fiddle: http://jsfiddle.net/4rRmp/
It seems that you are comparing an object to an integer in GmB >= upg.precio. You probably have to replace it by GmB.cantidad >= upg.precio.

Chrome Extension : Tab issues

The code below attempts to open a new tab for the corresponding post object, when its image is clicked in popup.html. For some reason, the new tab is blank and isn't going to the right page as specified by this.Link in the Post singleton. Any help would be appreciated!
<html>
<head>
<style>
body {
min-width:357px;
overflow-x:hidden;
}
img {
margin:5px;
border:2px solid black;
vertical-align:middle;
width:75px;
height:75px;
}
</style>
<script>
var req = new XMLHttpRequest();
req.open(
"GET",
"http://thekollection.com/feed/",
true);
req.onload = showPosts;
req.send(null);
function showPosts() {
var elements = req.responseXML.getElementsByTagName("item");
for (var i = 0, item; item = elements[i]; i++) {
var description = item.getElementsByTagName("description")[0].childNodes[0].nodeValue;
var link = item.getElementsByTagName("link")[0].childNodes[0].nodeValue;
var txtLink = link.toString();
var txtDesc = description.toString();
var start = txtDesc.indexOf("\"") + 1;
var end = txtDesc.indexOf(".jpg") + 4;
var imgURL = txtDesc.substring(start, end);
var post = new function(){
this.Link = txtLink;
this.Description = txtDesc;
this.ImageURL = imgURL;
this.imgElement = document.createElement("image");
this.displayTab = function(){
chrome.tabs.create({'url' : this.Link}, function(tab){});
}
}
post.imgElement.addEventListener("click", post.displayTab, false)
post.imgElement.src = post.ImageURL;
document.body.appendChild(post.imgElement);
}
}
</script>
</head>
<body>
</body>
You register post.displayTab as an event listener on post.imgElement which means that the value of this will be post.imgElement when the event listener is called. Consequently, there is no Link property (this.Link is undefined). One way to avoid this problem would be registering the event handler differently:
post.imgElement.addEventListener("click", function() {
post.displayTab();
}, false)
post.displayTab is called as a method of the post object here so this variable will be set correctly. The other option is to stop using this in post.displayTab:
this.imgElement = document.createElement("image");
var me = this;
this.displayTab = function(){
chrome.tabs.create({'url' : me.Link}, function(tab){});
}
The me variable remembers the "correct" this value.

Categories

Resources