logo
down
shadow

Javascript move entire span with arrow keys


Javascript move entire span with arrow keys

Content Index :

Javascript move entire span with arrow keys
Tag : javascript , By : itsmegb
Date : November 23 2020, 09:01 AM

Hope this helps
Your code fails because (unfortunately) span elements do not fire keydown/keyup/keypress events - no, not even when they are part of a contenteditable.
$('p[contenteditable]').on('keydown', function (e) { 
    // Only handle event if ctrl+left / ctrl+right
    if (!e.ctrlKey || (e.which != 37 && e.which != 39)) return;
    // and selection is in a span.move
    var sel = document.getSelection();
    var node = sel.anchorNode;
    if (!node || node != sel.focusNode) return;
    // Text "[move text]" is in selection, get <span> parent
    if (node.nodeType == Node.TEXT_NODE) {
        node = node.parentNode;
    }
    if (!node || node.nodeName != 'SPAN' || node.className != 'move') return;

    // Do the magic
    moveSpan(node, e.which == 37); // 37: left, 39: right
    e.preventDefault();
    e.stopPropagation();
});

function moveSpan (span, toLeft) {
    var left = span.previousSibling;
    var right = span.nextSibling;

    if (!left || left.nodeType != Node.TEXT_NODE || !right || right.nodeType != Node.TEXT_NODE) return;
    if (toLeft && !left.length) return;
    if (!toLeft && !right.length) return;

    if (toLeft) {
        right.insertData(0, left.data[left.length - 1]);
        left.deleteData(left.length - 1, 1);
    } else {
        left.appendData(right.data[0]);
        right.deleteData(0, 1);
    }
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to move an image around with arrow keys javascript


Tag : javascript , By : NeedOptic
Date : March 29 2020, 07:55 AM
To fix the issue you can do I can't figure out what your game is about, and so don't know what to do with that code. However, since you mentioned you were having trouble with movement, I wrote a quick JavaScript movement engine just for you, complete with acceleration and deceleration. Use the arrow keys to move. The following code represents a complete HTML document, so copy and paste it into a blank text file and save as .html. And make sure you have a 10x10 image called '1.png' in the same folder as the file.
<html>
<head>
<script type='text/javascript'>

// movement vars
var xpos = 100;
var ypos = 100;
var xspeed = 1;
var yspeed = 0;
var maxSpeed = 5;

// boundary
var minx = 0;
var miny = 0;
var maxx = 490; // 10 pixels for character's width
var maxy = 490; // 10 pixels for character's width

// controller vars
var upPressed = 0;
var downPressed = 0;
var leftPressed = 0;
var rightPressed = 0;

function slowDownX()
{
  if (xspeed > 0)
    xspeed = xspeed - 1;
  if (xspeed < 0)
    xspeed = xspeed + 1;
}

function slowDownY()
{
  if (yspeed > 0)
    yspeed = yspeed - 1;
  if (yspeed < 0)
    yspeed = yspeed + 1;
}

function gameLoop()
{
  // change position based on speed
  xpos = Math.min(Math.max(xpos + xspeed,minx),maxx);
  ypos = Math.min(Math.max(ypos + yspeed,miny),maxy);

  // or, without boundaries:
  // xpos = xpos + xspeed;
  // ypos = ypos + yspeed;

  // change actual position
  document.getElementById('character').style.left = xpos;
  document.getElementById('character').style.top = ypos;

  // change speed based on keyboard events
  if (upPressed == 1)
    yspeed = Math.max(yspeed - 1,-1*maxSpeed);
  if (downPressed == 1)
    yspeed = Math.min(yspeed + 1,1*maxSpeed)
  if (rightPressed == 1)
    xspeed = Math.min(xspeed + 1,1*maxSpeed);
  if (leftPressed == 1)
    xspeed = Math.max(xspeed - 1,-1*maxSpeed);

  // deceleration
  if (upPressed == 0 && downPressed == 0)
     slowDownY();
  if (leftPressed == 0 && rightPressed == 0)
     slowDownX();

  // loop
  setTimeout("gameLoop()",10);
}

function keyDown(e)
{
  var code = e.keyCode ? e.keyCode : e.which;
  if (code == 38)
    upPressed = 1;
  if (code == 40)
    downPressed = 1;
  if (code == 37)
    leftPressed = 1;
  if (code == 39)
    rightPressed = 1;
}

function keyUp(e)
{
  var code = e.keyCode ? e.keyCode : e.which;
  if (code == 38)
    upPressed = 0;
  if (code == 40)
    downPressed = 0;
  if (code == 37)
    leftPressed = 0;
  if (code == 39)
    rightPressed = 0;
}

</script>

</head>

<body onload="gameLoop()" onkeydown="keyDown(event)" onkeyup="keyUp(event)" bgcolor='gray'>

   <!-- The Level -->
   <div style='width:500;height:500;position:absolute;left:0;top:0;background:black;'>
   </div>

   <!-- The Character -->
   <img id='character' src='1.png' style='position:absolute;left:100;top:100;height:10;width:10;'/>

</body>

</html>

JavaScript move an image with arrow keys


Tag : javascript , By : kuba53280
Date : March 29 2020, 07:55 AM
may help you . I've seen lots of people ask similar questions here, but none of them seem to work for me. I have an img, with the id 'character'. I want it to move left on left click and right on right click. This is the code I have: , Why not use jQuery?
$("body").keydown(function(e) {
  var max = $('body').width();
  var min = 0;
  var move_amt = 10;
  var position = $("#my_image").offset();
  if(e.which == 37) { // left
    var new_left = ((position.left-move_amt < min) ? min : position.left-move_amt);
    $("#my_image").offset({ left: new_left})
  }
  else if(e.which == 39) { // right
    var new_left = ((position.left+move_amt > max) ? max : position.left+move_amt);
    $("#my_image").offset({ left: new_left})
  }
});

How to move an object using arrow keys using javascript


Tag : javascript , By : user178709
Date : March 29 2020, 07:55 AM
This might help you Going through with the code gdros and yourself provided:
Fiddle: https://jsfiddle.net/k3akqz3c/1/
// Basic variables
var canvas;
var context;
var rectX = 10;
var rectY = 10;

// Set canvas context
window.onload = function() {
    canvas = document.getElementById("myCanvas");
    context = canvas.getContext("2d");
}

function fillRect() {
    context.beginPath();
    context.fillStyle = "#ffffff";
    context.fillRect(0, 0, 1000 + canvas.width, 1000 + canvas.height);
    context.beginPath();
    context.fillStyle = "#666666";

    // Check if the rect isn't out of bounds, if so: place it back.
    if (rectX < 0) {
        rectX = 0;
    } else if (rectX > 250) {
        rectX = 250;
    }
    if (rectY < 0) {
        rectY = 0;
    } else if (rectX > 100) {
        rectX = 100;
    }

    context.fillRect(rectX, rectY, 50, 50);
}

function onkeydown(e) {
    if (e.keyCode == 39) {
        rectX++;
    } //right arrow
    else if (e.keyCode == 37) {
        rectX--;
    } //left arrow
    else if (e.keyCode == 38) {
        rectY--;
    } //up arrow
    else if (e.keyCode == 40) {
        rectY++;
    } //down arrow
    fillRect();
}
window.addEventListener("keydown", onkeydown);

Multiple contentEditable, unable to move carret to end of span with arrow keys


Tag : javascript , By : Shawazi
Date : March 29 2020, 07:55 AM
around this issue It seems like a browser bug. It is only happening in Firefox for me, however, adding any amount of padding to the spans seems to correct the issue:
span[contentEditable] { padding: 1px; }

how to move a image with arrow keys and get id of behind div in javascript?


Tag : javascript , By : Lars
Date : March 29 2020, 07:55 AM
Hope this helps Following up to my comments above,
document.elementFromPoint only gets the top most element - mozilla docs, which here is the image itself, so use a work around like setting display:none or pointer-events:none to the image to make the box as the top most elem and get the box Id. Then reset the value back.
Related Posts Related QUESTIONS :
  • How to send Id and file to same controller?
  • How to Make a jQuery Table Cell(td) clickable to Run a Function?
  • Prevent the duplicate function onchange event jQuery
  • Reactjs Input Upload doesn't return local URL
  • An unexpected 'StartObject' node was found when reading from the JSON reader. A 'PrimitiveValue' node was expected
  • How to filter a JSON Array, with an eventListener input value at keyup
  • How to separate the different properties of filter in css?
  • Why dont work change event of bootstrap input spinner?
  • How to hide overflow text content in react
  • Is there another way to write line 6
  • Cypress - how to find by text content?
  • How to setstate for the dynamic checkboxes in a loop in react?
  • Is display:none safe?
  • How to create a form to change part of a href url of a button?
  • Put many function inside function in Javascript
  • how to exit from loop after a ajax call
  • Do Angular Reactive Form Validator.min/max check Perform Type Conversions before checking the value?
  • How to Replace Text Within Script Tags Using JQuery
  • add variable to object if not undefined using short-hand
  • How can I effectively curve my items inside a list?
  • Add new record Keyboard Shortcut on Kendo Grid Mvc
  • Time and Date running on page
  • Looping through page links puppeteer doesn't return values from the newly loaded page
  • Problem with Navigator.geoLocation.getCurrentPosition not working
  • Trying to change the id of an element with Javascript
  • Embedded Schema Inserting Blank in Meteor using Collection2
  • avoid useEffect to render at first load?
  • Why is this CSS transition only working correctly on the some clicks? How to solve it?
  • Interpolated values does not reflect the latest values in an Angular app
  • Javascript classes define attribute in constructor or outside the class
  • How to block scroll event passing through to iframe until iframe is active?
  • What is the purpose of "constructor" method in javascript?
  • Stencil JS not working with non-default imports
  • Are frameworks misleadingly named for marketing purposes?
  • React <Redirect> after transition not working
  • How to send multiple parameters in a function using EJS
  • React conditional style on custom click
  • Push a block of information to an array X times based on an external variable
  • How do I populate dropdown with names, and values (numeric ids)?
  • How to apply styling to elements created with .insertAdjacentHtml method
  • Positioning key:value of an object
  • Referencing DOM Elements with React Hooks
  • TypeError: Method "getRange" of null when using multiple scripts (Libraries) in Google scripts
  • Why can't I check if an environment variable is undefined?
  • Is there a way to find what parts are the same between two strings?
  • Every change done with magicscroll and greensock get reset when I hit the bottom of the page
  • Fix a 'Cannot read property handleClick of undefined error' (and issues related to deleting an item from the DOM)
  • Answer to message if sent within a period of time
  • Enabling a button based on selected values
  • Get All possible matches between forward slashes
  • get the CSS maxWidth value of the parent javascript
  • Async function returning existing array as undefined
  • Using drop-down list to change multiple values in separate table cells
  • How to remove nested empty objects in JavaScript?
  • Convert value from text field to paragraph
  • Sorting a list based on instructions in Javascript
  • Post request doesn't work in NodeJS, OK with Request
  • How to make footer align to center in nested component scenario in React
  • fresh installed pwa does not show content
  • Working around unset "length" property on partial functions created with lodash's partialRight
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com