JeniOst
JeniOst

Reputation: 3

Dynamically resizing div width

I'm trying to create a custom HTML5 video slider (looks like youtube with the red line). It's composed of two divs one on top of the other, and the width of the red div needs to change according to the current video position.

I succeed catching the video position, but am unable to change the red div's width. what am I doing wrong?

HTML:

<video id="VideoWindow" src="../html/media/homepage.mp4" ontimeupdate="VideoTimeUpdated()"/>
<div id="PlaybackIndicatorProgress" style="left: 0%; width: 30%; display: block; background-color: red; height: 3px">

JS:

function VideoTimeUpdated() {
    var myVideo = document.getElementById("VideoWindow");
    var myVideoSlider = document.getElementById("PlaybackIndicatorProgress");
    var CurrentPosition;

    CurrentPosition = Math.round(parseInt(myVideo.currentTime / myVideo.duration * 100));
    CurrentPosition = CurrentPosition + '%'; 
    myVideoSlider.css("width", "CurrentPosition");
}

Thanks!

Jeni.

Upvotes: 0

Views: 555

Answers (2)

user2948666
user2948666

Reputation:

To me it looks like you are mixing jQuery and normal javascript here, try this for line 8 in your code:

myVideoSlider.style.width = CurrentPosition;

Explanation: the .css() method is a jQuery method, but you are getting your DOM node (The element you want to change) via the native getElementById() method, so you cannot use .css().

Dimitar is also partially right, since you want to use an variable you cannot set it into quotion marks, otherwise it would be interpreted as a string.

For line 6 to 8 i can say that you are casting (changing) a lot of "data types" around and use rounding which is not really needed, if you use a percentage for the width you can actually use float numbers. You can save two lines of code at the same time by merging line 6, 7 and 8 together:

myVideoSlider.style.width = (myVideo.currentTime / myVideo.duration * 100) + "%";

Please note that i put the calculations into brakets to separate them from the concatination (+ sign), otherwise it could be unclear if you read the code what is happening here since in javascript the plus sign is used for calculations and concatination of strings depending of the "data types" you use.

Upvotes: 1

Dimitar Popov
Dimitar Popov

Reputation: 696

CurrentPosition needs to be outside "", because your way "CurrentPosition" is just a string, not a variable.

It should be myVideoSlider.css("width", CurrentPosition);

Upvotes: 0

Related Questions