I found a helpful video tutorial on inline SVGs that I am using as a reference. My goal is to recreate the effect of an SVG line appearing to draw itself from its middle point outwards. The method described in the video involves setting the stroke-dasharray property to '0, length/2' and the stroke-dashoffset property to '-length/2', starting the line at its middle point. However, the challenge arises for me because my SVG line length is variable, unlike the predefined length in the video.
The technique seems simple: create an SVG line, set initial properties, and then adjust them when needed. In theory, changing the dasharray and dashoffset should make the line appear to draw itself from the middle outwards. But when I tried this with lines of unknown lengths, the line started drawing from almost the beginning instead of the middle. I used JavaScript to calculate the line length dynamically. Below is a snippet of my code.
function animateLine() {
const input = document.querySelector('.input');
const line = document.querySelector('.focus');
const length = line.getTotalLength();
line.style.strokeDasharray = `0, ${length/2}`;
line.style.strokeDashoffset = `-${length/2}`;
input.addEventListener('focus', function() {
line.style.strokeDasharray = `${length}, 0`;
line.style.strokeDashoffset = `0`;
});
};
animateLine();
/* Input module */
.input {
background: none;
border: none;
width: 100 %;
padding: 0.5em;
padding-left: 0;
color: white;
font-family: inherit;
font-size: 0.85em;
}
.input:focus {
outline: none;
}
.line {
width: 100%;
height: 2px;
padding: 0;
stroke: grey;
}
.focus {
stroke: black;
transition: all 5s;
stroke-dasharray: 0, 10000;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input class="input" type="text" name="review[body]" placeholder="Leave a review..." required>
<svg xmlns="http://www.w3.org/2000/svg" class="line" viewBox="0 0 40 2" preserveAspectRatio="none">
<path d="M0 1 L40 1"></path>
<path d="M0 1 L40 1" class="focus"></path>
</svg>
</body>
</html>
I experimented with different approaches, like percentages and fixed values, but couldn't solve the issue. Could anyone provide insight into what might be causing the problem?