I am trying to create a utility to help mobile users share a YouTube link and have it start at a specified time (YouTube does not offer this feature in their mobile website and apps).
The user pastes their link:
e.g. https://www.youtube.com/watch?v=rHcQy8jdAGY
They can then add values into the hour, minute and second fields.
As they do so, the final link is being built for them to copy and share.
The final link will look something like this:
https://www.youtube.com/watch?v=rHcQy8jdAGY&t=1h1m1s
...and thus the video will start at the 1:01:01 mark.
I have begun to build my utility in this CodePen.
What I can't figure out is how to append the TIME values — if and when they are added by the user — to the URL field.
When a value is added to any of the fields, the &t=
part of the URL needs to be appended first.
And although it doesn't matter what order the h/m/s values appear in the URL, it would be nice to keep them in order.
BTW I am a total hack, but I can usually muddle my way through these things eventually (with a little help).
CodePudding user response:
Use the URL API and the searchparams
const $urlField = $('input[name=URL]');
$('#container').on('input', function() {
let url;
try {
url = new URL($("#link").val());
}
catch {
$urlField.val("Please paste a valid URL")
return
}
let [h, m, s] = $("#time-wrap input").map(function() {
return this.value.trim()
}).get()
let time = "";
time = h ? `${h}h` : "";
time = m ? `${m}m` : "";
time = s ? `${s}s` : "";
url.searchParams.set("t",time)
console.log(time,url.toString())
$urlField.val(url.toString());
});
[name=URL] {
width: 300px;
font-size: 14px;
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<input id="link" type="url" placeholder="Paste the link to your video">
<div id="time-wrap">
<input placeholder="Hour">
<input placeholder="Minute">
<input placeholder="Second">
</div>
<input type="text" id="result-field" name="URL" placeholder="" value="Your sharing link will appear here">
<br />
</div>
<button onclick="copyFunction()">Copy text</button>