Home > Blockchain >  How do i move the flashing cursor along the text as if its a normal cursor with the 2 buttons? If po
How do i move the flashing cursor along the text as if its a normal cursor with the 2 buttons? If po

Time:04-07

My goal is to have it move back and forth with the button presses as if its an actual cursor

<div>
hello<span id="hi"></span>
</div>

<button onclick="move('left')">left</button>
<button onclick="move('right')">right</button>

i can't figure out how to locate the span in the text and then move it to the side with the button presses so it goes from hello| to hell|o with one press to the left

function move(direction){
      switch (direction) {

        case "left":
            break;

        case "right":
            break;
    }
}

all the css is fine

 span {
  content: '';
  width: 3px;
  height: 17px;
  background: black;
  opacity: 0;
  display: inline-block;
  animation: blink 0.5s linear infinite alternate;
}
@keyframes blink {
  50% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

CodePudding user response:

The way you need to think about this is that your document is a tree (as in the data structure) because that is how the browser sees it. That means means the part that you are working with is three sections:

div
.....[text]
..... span
.....[text]
div

All three are children of your parent div, so they will be in its childNodes collection. Two are text nodes, the other is a span element.

The text node type has a textContent property, which you can use to get or set the text within the node. Something like this:

const myDiv = document.getElementsByTagName('div')[0]; // assuming you only have one div, more practical to give your div an id and use document.getElementById("my-id");
myDiv.childNodes[0].textContent = "hello";

This looks a little homework-adjacent and certainly seems a good opportunity for learning, so instead of writing the code, I'll take the long cut. The process I would go through in your function is:

  1. Find the parent div - perhaps having an id on it would make that easier.
  2. Read the textContent of its first child.
  3. Read the textContent of its last child.
  4. If you're moving left you want to remove the last character from the first child and put it on the start of the last child. If the first child is empty, do nothing.
  5. If you're moving right you want to remove the first character of the last child and put it on the last character of the first child. If the last child is empty, do nothing.

Note that doing it this way, we aren't doing anything with the span we are moving the text around it instead.

For extra flourish you could create an object that maintains references to the text nodes in question so you don't have to retrieve them each time a button is clicked.

  • Related