最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to get the value of the hovered time on input range - Stack Overflow

programmeradmin0浏览0评论

my question may have been a bit vague so ill explain it in detail here. im trying to develop a simple video player on a page. im using input range to display the file duration and current time like any standard player. here is my script.

<script>
        var vid, playbtn, seekslider, curtimeText, durtimeText, mutebtn, volumeslider, fullscreenbtn;
        function initializePlayer() {

            //creating global object
            vid = document.getElementById('my_video');
            playbtn = document.getElementById('playpausebtn');
            seekslider = document.getElementById('seekslider');
            curtimeText = document.getElementById('curtimeText');
            durtimeText = document.getElementById('durtimeText');
            mutebtn = document.getElementById('mutebtn');
            volumeslider = document.getElementById('volumeslider');
            fullscreenbtn = document.getElementById('fullscreenbtn');

            //creating event for objects
            playbtn.addEventListener("click", playPause, false);
            seekslider.addEventListener("change", vidSeek, false);
            vid.addEventListener("timeupdate", seektimeupdate, false);
            mutebtn.addEventListener("click", vidmute, false);
            volumeslider.addEventListener("change", setvolume, false);
            fullscreenbtn.addEventListener("click", toggleFullScreen, false);
        }

        window.onload = initializePlayer;

        function playPause() {
            if (vid.paused) {
                vid.play();
                playbtn.innerHTML = "Pause";
            } else {
                vid.pause();
                playbtn.innerHTML = "Play";
            }

        }
        function vidSeek() {
            var seekto = vid.duration * (seekslider.value / 100);
            vid.currentTime = seekto;
        }
        function seektimeupdate() {
            var nt = vid.currentTime * (100 / vid.duration);
            seekslider.value = nt;
            var curmins = Math.floor(vid.currentTime / 60);
            var cursecs = Math.floor(vid.currentTime - curmins * 60);
            var durmins = Math.floor(vid.duration / 60);
            var dursecs = Math.floor(vid.duration - durmins * 60);
            if (cursecs < 10) {
                cursecs = "0" + cursecs;
            }
            if (dursecs < 10) {
                dursecs = "0" + dursecs;
            }
            if (curmins < 10) {
                curmins = "0" + curmins;
            }
            if (durmins < 10) {
                durmins = "0" + durmins;
            }
            curtimeText.innerHTML = curmins + ":" + cursecs;
            durtimeText.innerHTML = durmins + ":" + dursecs;
        }
        function vidmute() {

            if (vid.muted) {
                vid.muted = false;
                mutebtn.innerHTML = "Mute";
            } else {
                vid.muted = true;
                mutebtn.innerHTML = "Unmute";
            }
        }
        function setvolume() {
            vid.volume = volumeslider.value / 100;
        }
        function toggleFullScreen() {
            if (vid.requestFullScreen) {
                vid.requestFullScreen();
            } else if (vid.webkitRequestFullScreen) {
                vid.webkitRequestFullScreen();
            } else if (vid.mozRequestFullScreen) {
                vid.mozRequestFullScreen();
            }
        }
</script>

and my HTML code:

<div id="Video_player_box">
    <video id="my_video">
        <source src="Videos/cowhand.mp4" type="video/mp4">
        <!-- Your browser does not support HTML5 video.-->
    </video>
    <div id="Video_controls_bar">
        <button id="playpausebtn">Play</button>             
        <span id="curtimeText"></span>
        <input id="seekslider" type="range" min="0" max="100" value="0" step="0.1"> 
        <span id="durtimeText"></span>
        <button id="mutebtn">Mute</button>
        <input id="volumeslider" type="range" min="0" max="100" value="50" step="1">
        <button id="fullscreenbtn">[&nbsp;&nbsp;]</button>
    </div> 
</div>

now what i want to do is to display the time of wherever the user is pointing at seekslider on a small tooltip. like if the video is 10min long, and the user is point at the middle of the rangebar (seekslider) i want a small tooltip to shows that the user is pointing at i.e 5:01 but i really have no idea on how to code that! i would appreciate any kind of help on how to implement this function.

my question may have been a bit vague so ill explain it in detail here. im trying to develop a simple video player on a page. im using input range to display the file duration and current time like any standard player. here is my script.

<script>
        var vid, playbtn, seekslider, curtimeText, durtimeText, mutebtn, volumeslider, fullscreenbtn;
        function initializePlayer() {

            //creating global object
            vid = document.getElementById('my_video');
            playbtn = document.getElementById('playpausebtn');
            seekslider = document.getElementById('seekslider');
            curtimeText = document.getElementById('curtimeText');
            durtimeText = document.getElementById('durtimeText');
            mutebtn = document.getElementById('mutebtn');
            volumeslider = document.getElementById('volumeslider');
            fullscreenbtn = document.getElementById('fullscreenbtn');

            //creating event for objects
            playbtn.addEventListener("click", playPause, false);
            seekslider.addEventListener("change", vidSeek, false);
            vid.addEventListener("timeupdate", seektimeupdate, false);
            mutebtn.addEventListener("click", vidmute, false);
            volumeslider.addEventListener("change", setvolume, false);
            fullscreenbtn.addEventListener("click", toggleFullScreen, false);
        }

        window.onload = initializePlayer;

        function playPause() {
            if (vid.paused) {
                vid.play();
                playbtn.innerHTML = "Pause";
            } else {
                vid.pause();
                playbtn.innerHTML = "Play";
            }

        }
        function vidSeek() {
            var seekto = vid.duration * (seekslider.value / 100);
            vid.currentTime = seekto;
        }
        function seektimeupdate() {
            var nt = vid.currentTime * (100 / vid.duration);
            seekslider.value = nt;
            var curmins = Math.floor(vid.currentTime / 60);
            var cursecs = Math.floor(vid.currentTime - curmins * 60);
            var durmins = Math.floor(vid.duration / 60);
            var dursecs = Math.floor(vid.duration - durmins * 60);
            if (cursecs < 10) {
                cursecs = "0" + cursecs;
            }
            if (dursecs < 10) {
                dursecs = "0" + dursecs;
            }
            if (curmins < 10) {
                curmins = "0" + curmins;
            }
            if (durmins < 10) {
                durmins = "0" + durmins;
            }
            curtimeText.innerHTML = curmins + ":" + cursecs;
            durtimeText.innerHTML = durmins + ":" + dursecs;
        }
        function vidmute() {

            if (vid.muted) {
                vid.muted = false;
                mutebtn.innerHTML = "Mute";
            } else {
                vid.muted = true;
                mutebtn.innerHTML = "Unmute";
            }
        }
        function setvolume() {
            vid.volume = volumeslider.value / 100;
        }
        function toggleFullScreen() {
            if (vid.requestFullScreen) {
                vid.requestFullScreen();
            } else if (vid.webkitRequestFullScreen) {
                vid.webkitRequestFullScreen();
            } else if (vid.mozRequestFullScreen) {
                vid.mozRequestFullScreen();
            }
        }
</script>

and my HTML code:

<div id="Video_player_box">
    <video id="my_video">
        <source src="Videos/cowhand.mp4" type="video/mp4">
        <!-- Your browser does not support HTML5 video.-->
    </video>
    <div id="Video_controls_bar">
        <button id="playpausebtn">Play</button>             
        <span id="curtimeText"></span>
        <input id="seekslider" type="range" min="0" max="100" value="0" step="0.1"> 
        <span id="durtimeText"></span>
        <button id="mutebtn">Mute</button>
        <input id="volumeslider" type="range" min="0" max="100" value="50" step="1">
        <button id="fullscreenbtn">[&nbsp;&nbsp;]</button>
    </div> 
</div>

now what i want to do is to display the time of wherever the user is pointing at seekslider on a small tooltip. like if the video is 10min long, and the user is point at the middle of the rangebar (seekslider) i want a small tooltip to shows that the user is pointing at i.e 5:01 but i really have no idea on how to code that! i would appreciate any kind of help on how to implement this function.

Share Improve this question asked May 27, 2015 at 4:26 CodeMonkeyCodeMonkey 2,5234 gold badges28 silver badges38 bronze badges 1
  • There should be a straight forward way to acplish this... but otherwise you could use a mousemove event: take the clientX and figure out where your mouse is relative to the slider. From there you could create a percentage that can be used to calculate 'current' seek position. – Jesse Kernaghan Commented May 27, 2015 at 5:00
Add a ment  | 

4 Answers 4

Reset to default 4

Here is a simple function that should get you on your way. It uses the event data to get all the necessary numbers and returns a value based on the slider's max attribute.

function calcSliderPos(e) {
  return ( e.clientX - e.target.offsetLeft ) / e.target.clientWidth * parseFloat(e.target.getAttribute('max'));
}

//attach to slider and fire on mousemove
document.getElementById('seekslider').addEventListener('mousemove', function(e) {
  //inject the value into the durtime span
  document.getElementById('durtimeText').innerHTML = calcSliderPos(e).toFixed(2);
});
<input id="seekslider" type="range" min="0" max="100" value="0" step="0.1"> 
<span id="durtimeText"></span>
        

Note that this only gives you an estimated position. I believe the only way to really get an 100% accurate position is to select a spot on the slider and fetch that value.

Drawing on Jesse's answer as well as this page and some of my own experimentation, I took it a step further and figured out the code to get the tooltip to follow the mouse.

I created a Codepen for your code, Ali, and added a function to handle the tooltip. You can check out the full code there, but here's what I added to your original code:

In the HTML, I wrapped your seekslider in a container and added a span for the tooltip like so:

<div id="seek-container">
    <input id="seekslider" type="range" min="0" max="100" value="0" step="0.1" /><span id="seek-tooltip"></span>
</div>

Then, with CSS, I:

  • Ensured that the seek-container would remain inline like the slider ordinarily would.
  • Set the seek-tooltip position to be absolute, or relative to the document (you'll see why in a bit), set it to be initially invisible, and gave it a nice shadow just for kicks.
  • Made the seek-tooltip bee visible with a white background when the seek-container is hovered over.

This was the code to do all that:

#seek-container {
    display: inline;
}

#seek-tooltip {
    position: absolute;
    display: none;
    box-shadow: 5px 5px 8px #CCC;
}

#seek-container:hover #seek-tooltip {
    display: inline;
    background: #fff;
}

Finally, the good stuff: JavaScript. Now, despite the fact that you tagged this question jQuery, I noticed that your original code didn't include any, so I chose to follow your suit and not use jQuery in this answer. It's of course doable (likely a little easier), but I wanted this to flow as consistently as possible with what you already had.

Anyway, here's what I did:

  • Added another variable to your list at the start: tooltip
  • Stored the seek-tooltip element into that tooltip variable
  • Added a mousemove event listener to your seekslider that called the function sliderTooltip
  • Wrote the function sliderTooltip, which calculated the currently hovered time (thanks Jesse), set the contents of the tooltip to the time, set the tooltip's top position to that of the slider, and set the tooltip's left position to that of the mouse. This is why the tooltip's position is set to absolute: I'm using the offsetTop property of the slider to determine the necessary y-coordinate and the pageX property to grab the mouse's x-coordinate, both of which are relative to the document; making the tooltip positioned absolutely ensures that the tooltip and mouse are using the same coordinates.

Here's the code:

var tooltip; //This would be at the beginning with your other definitions

//--The stuff below would be inside your window.onload function--

//Populate your tooltip variable
tooltip = document.getElementById("seek-tooltip");
 //Bind the tooltip update function to the slider's mousemove event
seekslider.addEventListener("mousemove", sliderTooltip, false);

//--Done with the stuff in your window.onload--

function sliderTooltip(e) { 
    //The parameter e is the mousemove event that was fired
    //First, calculate the current hovered time (thanks Jesse)
    var hoverTime = ((e.clientX - e.target.offsetLeft) / e.target.clientWidth * parseFloat(e.target.getAttribute('max'))).toFixed(2);
    var hoverMins = Math.floor(hoverTime / 60);
    var hoverSecs = Math.floor(hoverTime - hoverMins * 60);

    //Now that we've got the time, simply populate the tooltip!
    tooltip.innerHTML = hoverMins + ":" + hoverSecs;
    //Set the "top" CSS to the top position of the slider
    tooltip.style.top = seekslider.offsetTop + "px";
    //Set the "left" CSS to our mouse position, plus 10 pixels
    //to offset it a bit to allow the user to click on the slider and not on the tooltip
    tooltip.style.left = (e.pageX + 10) + "px";

} }

If you're curious as to what the jQuery version would have looked like, it's close to exactly the same thing, save for the way the tooltip is selected and its event listener is added.

I have tried jming's answer but to me, totally wrong value was being provided. After modifying like below, my problem was solved.

var hoverTime = (e.offsetX / e.target.clientWidth) * parseInt(e.target.getAttribute('max'),10);

This provides more accurate value of the time inside the slider.

Thanks to jming for his awesome work.

Hi there i was working on this tooltip of current Time project and i got a script that i made myself that actually works just awesome it is the mixture of every code i have seen for this project

 var video = $('video')[0];
 $('input').mousemove(function(e){
        var progress = $("input");
        var maxduration = video.duration;
        var position = e.pageX - progress.offset().left;
        var tooltip = $("span")[0];
        var percentage = 100 * position / progress.width();
        if (percentage > 100) {
            percentage = 100;
        }
        if (percentage < 0) {
            percentage = 0;
        }
        var min = Math.floor((percentage / 100 * video.duration) / 60);
        var sec = Math.floor((percentage / 100 * video.duration) - min * 60); 
        if(min < 10){
            min = "0" + min;
        }
        if(sec < 10){
            sec = "0" + sec;
        }
        $("span").html(min + ":" + sec); 
  //You can use this code below to align your tooltip when you have pleted styling it
  /*tooltip.style.top = -progress[0].offsetTop+(-10) + "px";
         console.log(progress.offset().top);
         tooltip.style.marginLeft = (e.pageX - 25) + "px";
  //Note: You may have to edit this code according to your styling
*/
});
//Just for testing
var timeDrag = false;
$('input').on('mousedown', function(e) {
        timeDrag = true;
        video.pause();
        updatebar(e.pageX);
 });
   var updatebar = function(x) {
        var progress = $('input');

        //calculate drag position
        //and update video currenttime
        //as well as progress bar
        var maxduration = video.duration;
        var position = x - progress.offset().left;
        var percentage = 100 * position / progress.width();
        if (percentage > 100) {
            percentage = 100;
        }
        if (percentage < 0) {
            percentage = 0;
        }
        video.currentTime = maxduration * percentage / 100;
    };
 
input{
  width:400px; /*Just for demonstration that this code does not depend on width of the slider*/
}
<script src="https://ajax.googleapis./ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<video src="https://givemesomething.000webhostapp./video.mp4" height="280" width="100%" controls></video> 
<input type="range" min="0" max="100" value="0">
<span></span>

That's All it will work surely work thanks

发布评论

评论列表(0)

  1. 暂无评论