I created a custom text cursor using CSS:
.cursor {
position: relative;
}
.cursor i {
position: absolute;
width: 10px;
height: 80%;
background-color: blue;
left: 5px;
top: 10%;
animation-name: blink;
animation-duration: 1s;
animation-iteration-count: infinite;
opacity: 1;
}
@keyframes blink {
from {
opacity: 1;
}
to {
opacity: 0.5;
}
}
The above CSS is implemented in the following HTML:
<div >
<input type="text" />
<i></i>
</div>
Although this successfully creates a blinking, rectangular, and blue text cursor, it remains in the same position once I type text into the input box. How can I modify the above code so that the cursor moves, similar to Mac/Linux terminals?
CodePudding user response:
You need to get value of your input and put it inside a hidden div to get the clientWidth.
Make sure that you set the same font family and the same font size for your input and the div "mask" to make it work correctly.
I added 3 px to make a correction.
I used css css() for the left move.
let elemDiv = document.getElementById("mask"),
elemInput = document.getElementById("typing");
elemInput.oninput = function() {
elemDiv.innerText = elemInput.value;
// css version
$(".cursor i").css({"left":(elemDiv.clientWidth 3) "px"});
// debug infos
console.clear();
console.log((elemDiv.clientWidth 3) "px");
}
.cursor {
position: relative;
}
.cursor i {
position: absolute;
width: 10px;
height: 80%;
background-color: blue;
left: 5px;
top: 10%;
animation-name: blink;
animation-duration: 1s;
animation-iteration-count: infinite;
opacity: 1;
}
#typing {
width:100%;
font-family:arial;
font-size:12px;
}
#mask {
font-family:arial;
font-size:12px;
width: auto;
display: inline-block;
visibility: hidden;
position: fixed;
overflow:auto;
}
@keyframes blink {
from {
opacity: 1;
}
to {
opacity: 0.5;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<input type="text" id="typing" />
<i></i>
</div>
<div id='mask'></div>
But you can also do it with animate().
let elemDiv = document.getElementById("mask"),
elemInput = document.getElementById("typing");
elemInput.oninput = function() {
elemDiv.innerText = elemInput.value;
// animated version
$(".cursor i").animate({"left":(elemDiv.clientWidth 3) "px"}, "fast");
// debug infos
console.clear();
console.log((elemDiv.clientWidth 3) "px");
}
.cursor {
position: relative;
}
.cursor i {
position: absolute;
width: 10px;
height: 80%;
background-color: blue;
left: 5px;
top: 10%;
animation-name: blink;
animation-duration: 1s;
animation-iteration-count: infinite;
opacity: 1;
}
#typing {
width:100%;
font-family:arial;
font-size:12px;
}
#mask {
font-family:arial;
font-size:12px;
width: auto;
display: inline-block;
visibility: hidden;
position: fixed;
overflow:auto;
}
@keyframes blink {
from {
opacity: 1;
}
to {
opacity: 0.5;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<input type="text" id="typing" />
<i></i>
</div>
<div id='mask'></div>