Weird error for use of keyCode should be working - javascript

I'm getting an error with my event.keyCode saying that
Cannot read property 'keyCode'
I want the code to when I press "I" to load the screen that I have drawn onto my canvas
var canvas = document.querySelector("canvas");
document.addEventListener('keydown', loadScreen);
canvas.width=640;
canvas.height=640;
var draw = canvas.getContext("2d");
loadScreen();
function loadScreen(event) {
var key = (event.keyCode);
if(key == 73)
{
InventoryScreen();
}
}
function InventoryScreen()
{
draw.fillStyle = "#D3D3D3";
draw.fillRect(50,50,100,80);
draw.fillRect(50,135,100,80);
draw.fillRect(50,220,100,80);
draw.fillRect(50,305,100,80);
draw.fillRect(50,390,100,80);
draw.fillRect(50,475,100,80);
draw.fillRect(495,50,100,80);
draw.fillRect(495,135,100,80);
draw.fillRect(495,220,100,80);
draw.fillRect(495,305,100,80);
draw.fillRect(495,390,100,80);
draw.fillRect(495,475,100,80);
draw.fillRect(155,50,335,505);
}

I think your issue is here:
loadScreen();
You are calling loadScreen without passing it an event.
You can fake it by doing this:
loadScreen({keyCode:73});
Note that when loadScreen is set to be called by an Event here:
document.addEventListener('keydown', loadScreen);
…every time a keyboard key is pressed down, an event object is passed as the first argument, and that event object contains a keyCode value that corresponds with the key pressed.
I was able to wrap your code in a test HTML document, and it produced some nice-looking gray rectangles:
<!DOCTYPE html>
<html>
<head>
<title>Test of Stackoverflow question 49583733</title>
<script type="text/javascript">
window.addEventListener('load', () => {
your code here, adding {keyCode:73}
}) ;
</script>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>

Related

How to access an iframe from chrome extension?

How can I get my extension to work on all frames like adblock does?
I tried adding "all_frames" : true to my manifest file but it didn't work.
I tried to use this code to get the text with specific ids:
var theId = "starts with something";
var myArray = [];
$('[id^="theId"]').each(function(i, obj) {
myArray.push($(this).text());
});
$.unique(myArray);
console.log(myArray);
but it says my array is empty. When I inspect element on the page, I see a "top" layer, and a "target content" layer. The code only works when I execute it in the console on the "target content" layer. Can I use this code in a content script, or do I need to use background.js somehow?
Continued from SO44122853
I see you figured out that the content was loaded in an iframe. So I have a working demo here PLUNKER, the snippet is here just in case the plunker goes down.
Details are commented in PLUNKER
Demo
Not functional due to the need to run 2 separate pages
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<style></style>
</head>
<body>
<!--iframe is same as the one on the site, with the exception
of the src-->
<iframe id="ptifrmtgtframe" name="TargetContent" title="Main Content" frameborder="0" scrolling="auto" width='90%' src="tables.html"></iframe>
<!--The data is displayed as a one string-->
<output id='display'></output>
<script>
// Reference the iframe
var iFID = document.getElementById("ptifrmtgtframe");
// Register the load event on iframe
iFID.onload = function(e) {
// Callback is extractText function
return extractText('#ptifrmtgtframe', '#display', '.PSLONGEDITBOX');
}
/* Pass iframe and display as a single selector
|| Pass targets as a multiple selector
*/
function extractText(iframe, display, targets) {
var iArray = [];
var iFrame = document.querySelector(iframe);
var iView = document.querySelector(display);
var iNode = "";
/* .contentWindow is property that refers to content
|| that is in an iframe. This is the heart of the
|| demo.
*/
var iContent = iFrame.contentDocument || iFrame.contentWindow.document;
var iTarget = iContent.querySelectorAll(targets);
/* .map() will call a function on each element
|| and return a new array as well.
*/
Array.from(iTarget).map(function(node, idx) {
iNode = node.textContent;
iView.textContent += iNode;
iArray.push(iNode);
return iArray;
});
console.log(iArray);
}
</script>
</body>
I think your script may be executing before the DOM loads, try putting your function inside:
document.addEventListener('DOMContentLoaded', function() {
});
EDIT
That event seems to do nothing in content scripts, I think that is because they are already loading after DOM is loaded, and never fires.
However this seems to fire but not sure why:
$(function(){
//something
});
This needs jQuery injected aswell

e.keyCode doesn't work

I'm new at programming and I do whatever I see in the youtube video to create a game with canvas. This code works in the video but doesn't work for me.I don't see key codes on the screen so key code thing doesn't work . I don't know what is wrong with the coding..
My codes:
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");
var keys[];
window.addEventListener("keydown", function(e) {
alert(e.keyCode);
}, false);
<html>
<head>
<title>GAME</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<canvas id="mainCanvas" width="500" height="400"></canvas>
<script src="script.js"></script>
</body>
</html>
Always, when developing, do it with an open console. You're receiving the following error: Uncaught SyntaxError: Unexpected token [.
That's because you don't create arrays in JS like that. You actually do: var arr = [];. Just change var keys[] to var keys = [];
jsFiddle : https://jsfiddle.net/02f6nyh9/
javascript
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");
var keys = new Array();
// var keys = []; // Either of these work
window.addEventListener("keydown", function(e) {
alert(e.keyCode);
}, false);
context.fillRect(0,0,500,400);
You just need to create an array correctly then it works fine :)

Fire an event before `cut` event in ace editor

I want to fire an event before cut, so that I can get what text is being cut i.e. what has been already selected. I am currently using the following code, which doesn't seem to work as desired.
$("#editor").bind({
cut:function(){
console.log('Cut Detected');
alert(editor.selection.getRange());
}
});
editor is the id of the "div" tag which is editable. editor.selection.getRange() returns the start and end of selection.
edit I am woring with content editable div and want to apply the functionality on it.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Editor</title>
</head>
<body>
<div id='myTa' contenteditable>hello world where are you</div>
<script type='text/javascript' src='jquery-2.1.4.min.js'></script>
<script type='text/javascript'>
$("#myTa").on("cut", function(){
alert(this.selectionStart+ " to " + this.selectionEnd);
})
</script>
</body>
</html>
You are correct that you need to use the cut event. The ClipboardEvent API is apparently unstable but yes, I would have thought it would include the text being moved onto the clipboard.
The following works for me:
$("textarea").on("cut", function(){
alert(this.value.substring(this.selectionStart, this.selectionEnd));
})
It's worth noting that bind is deprecated in jQuery, you should use on instead. Try out the snippet:
$("textarea").on("cut", function() {
alert(this.value.substring(this.selectionStart, this.selectionEnd));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
I think at first that clipboardEvent will have the clipped text, but it seems not, so I try to find the selection related properties of input and found it.
And the reference is HTMLInputElement.
This codes work in presumption that your $("#editor") is either an input or textarea.
$("#editor").bind({
cut:function(e){
console.log('Cut Detected');
var $this = $(this);
var selectStart = this.selectionStart;
var selectionEnd = this.selectionEnd;
var clippedValue = $this.val().slice(selectStart, selectionEnd);
// Now you have the clipped value, do whatever you want with the
// value.
alert(clippedValue);
}
});
For works on contentediable, you can do this, which I just found info from Return HTML from a user-selected text and MDN
$("#myTa").on("cut", function(e){
// Seems diff bro
var selections = window.getSelection();
var currentSelection = selections.getRangeAt(0);
var start = currentSelection.startOffset;
var end = currentSelection.endOffset;
var selectedContents = currentSelection.toString();
// Do whatever you want.
console.log(start, end);
console.log(selectedContents);
alert(selectedContents);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id='myTa' contenteditable>ask;ndjkasn asdbasj aujs d sdib askjbnsaab asbh mjn a</div>
I have got the solution to my answer. apperently there is an editor.on('cut',function(e)) in ace editor I use
editor.on("cut", function(e){
console.log('Cut Detected');
console.log(editor.selection.getRange());
});

Calling function from external JS

I am trying to call a function from an external .js file but the console is returning errors and the function is not being called. How do I correct my code and be able to call the function properly.
Here is the main .html file:
<html>
<head>
<script type="text/javascript" src="xp.js">
</script>
<script type="text/javascript">
window.onload = xyz.makeShape.Circle();
</script>
</head>
<body>
<canvas id="xyz" width="600" height="600"></canvas>
</body>
</html>
And here is the .js file:
var xyz = xyz || {};
var canvas = document.getElementById('xyz');
var context = canvas.getContext('2d');
xyz.makeShape = {
Circle : function() {
console.log('working');
}
}
EDIT
I am getting 2 errors in the console:
Error 1
TypeError: canvas is null
window.onload = xyz.makeShape.Circle;
Error 2
TypeError: xyz.makeShape is undefined
window.onload = xyz.makeShape.Circle;
Change this:
window.onload = xyz.makeShape.Circle();
to this:
window.onload = xyz.makeShape.Circle;
window.onload needs to be set to a function reference, not to the results of calling a function.
You also can't do these two lines from the <head> section before the DOM is loaded:
var canvas = document.getElementById('xyz');
var context = canvas.getContext('2d');
You need to execute those after the DOM has been loaded. There are multiple possible strategies for doing that. The easiest for what you already have would be to execute them in your onload handler since you know the DOM is already loaded there. You could also move the script tag that loads your external .js file to the end of the <body> section and the DOM will already be ready then when that js file runs.
You will just need to include the js file using the <script> tags - either in your header or footer.
<script type="text/javascript" src="js/yourjsfile.js"></script>
Now you can call functions from that script as if they were in the current file
Edit
If you're sure that the file is already included (first make sure you've got the path right) next you need to check your console from errors that may be arising from the included file. The code you've supplied looks right.
External js:
var xyz = xyz || {};
xyz.makeShape = {
Circle: function () {
console.log('working');
}
}
Internal js:
window.onload = function () {
var canvas = document.getElementById('xyz');
var context = canvas.getContext('2d');
xyz.makeShape.Circle();
}
Tested and works

issue getting mouse coordinate

I use below code to capture mouse coordinate, and bind it to a div(container). and there's one more div called subDiv inside container. I found that no matter where I move inside subDiv, the coordinate is always the one I just entered subDiv (e.g. I enter subDiv at (10,10), no mater where I move in subDiv, the coordinate is always (10,10)).
Anybody know why?
var x,y;
var e = e||window.event;
return {
x:e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,
y:e.clientY+document.body.scrollTop+document.documentElement.scrollTop
};
What you pasted works as following demos. Check other code.
<!DOCTYPE html>
<html>
<head>
<script>
function test(e){
var x,y;
var e = e||window.event;
return {
x:e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,
y:e.clientY+document.body.scrollTop+document.documentElement.scrollTop
};
}
function myFunction(event){
var x = test(event);
document.getElementById("demo").innerHTML=x.x + '.' + x.y;
}
</script>
</head>
<body>
<div id="container">
<div id="subDiv" style="width:199px;height:99px;border:1px solid" onmousemove="myFunction(event)"></div>
</div>
<p id="demo"></p>
</body>
</html>

Categories

Resources