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.
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.
CurrentPosition needs to be outside "", because your way "CurrentPosition" is just a string, not a variable.
It should be myVideoSlider.css("width", CurrentPosition);
Related
I am trying to create a javascript function that crops and centers image to 1000px. To do that, I take the width, subtract 1000, divide by 2, and multiply by -1. I then take this value and assign it to margin-left and margin-right. I have it set to run on page load. For some reason, it is not executing my first line of code. Take a look below. (debug alerts are for debug purposes)
Javascript
function crop()
{
alert("debug")
width = document.getElementById(slide).width
alert("debug")
width = -1((width - 1000)/2)
alert("debug")
document.getElementById(slide).setAttribute("style","margin-left" + width + "px")
alert("debug")
document.getElementById(slide).setAttribute("style","margin-right" + width + "px")
alert("debug")
}
This is the element I am trying to get it to apply all this to.
Element
<div id="mySlides" style="width:1000px; overflow:hidden;">
<img src="img/1.jpg" onclick="slideshow()" id="slide" />
</div>
As you can see, it only displays the first debug alert, and doesn't display anything else after that. Can somebody explain why it is ignoring the rest of the code?
slide is a reference to a variable named slide. You probably want "slide" (a string), as your img element has id="slide".
You should spend some time getting familiar with your browser's debugging tools (alert() is a horrible way of debugging). It would have pointed out...
ReferenceError: slide is not defined
You are missing delimiters around the string here:
width = document.getElementById("slide").width;
You are missing the multiplication operator here:
width = -1 * ((width - 1000)/2);
You are missing the string delimiters, and colons in the style declarations, and also you have to put the styles together otherwise the second one will overwrite the first:
document.getElementById("slide").setAttribute("style","margin-left:" + width + "px;margin-right:" + width + "px");
Is it possible to get the width (using javascript or jQuery) of a float-affected element? When text is being pushed over due to a floating image is it possible to get its position and true width? I have attached an image to explain better.
Code example,
<div>
<img style="...float: left"/>
<h1>A title!</h1>
<p>Text!</p>
<h1>New header added.</h1>
</div>
Picture
I need to find the width starting from the arrow, (the gray box is the image)(the dotted line is the width according to Firefox inspect mode).
I would like to avoid changing all the elements display types if possible.
Thank you!
I'm a little late to the party, but I had a similar problem and came up with a solution which (so far) seems to work in all instances of this issue. I like this solution because as far as I can tell, it works independent of the floating element - all you need is the element whose true width/position you want to get, nothing more. I've done it in pure Javascript for speed purposes, but it can easily be streamlined with jQuery and a separate CSS Stylesheet if you so choose.
//Get the rendered bounding box for the content of any HTMLElement "el"
var getLimits = function(el) {
//Set a universal style for both tester spans; use "!important" to make sure other styles don't mess things up!
var testerStyle = 'width: 0px!important; overflow: hidden!important; color: transparent!important;';
//Create a 'tester' span and place it BEFORE the content
var testerStart = document.createElement('SPAN');
testerStart.innerHTML = '|';
var testerFloat = ' float: left!important;';
testerStart.setAttribute('style', testerStyle + testerFloat);
//Insert testerStart before the first child of our element
if (el.firstChild) {
el.insertBefore(testerStart, el.firstChild);
} else {
el.appendChild(testerStart);
}
//Create a 'tester' span and place it AFTER the content
var testerEnd = document.createElement('SPAN');
testerEnd.innerHTML = '|';
testerFloat = ' float: right!important;';
testerEnd.setAttribute('style', testerStyle + testerFloat);
el.appendChild(testerEnd);
//Measure the testers
var limits = {
top: testerStart.offsetTop,
bottom: testerEnd.offsetTop + testerEnd.offsetHeight,
left: testerStart.offsetLeft,
right: testerEnd.offsetLeft
}
//Remove the testers and return
el.removeChild(testerStart);
el.removeChild(testerEnd);
return limits;
};
So, in your case, the code would just be:
var paragraphBoundingBox = getLimits($('div>p').get(0));
A couple things to note:
1) The float direction would be reversed if you are using an RTL language
2) All of the four edge positions in the output object are relative to the el.offsetParent - use this handy function can find their positions relative to the document.
First of all, the "full width" is exactly the true width.
You can watch this picture, it can help you understand why the true width and true position of the affected element is the way firefox tells you.
http://i.stack.imgur.com/mB5Ds.png
To get the width of inline text where it's pushed right by the float image, there's no good way except using the full width minus the float image's width.
var w = $('p').width()
- $('img').width()
- $('img').css('margin-left').replace("px", "")
- $('img').css('margin-right').replace("px", "")
- $('img').css('padding-left').replace("px", "")
- $('img').css('padding-right').replace("px", "")
- $('img').css('border-left-width').replace("px", "")
- $('img').css('border-right-width').replace("px", "");
I've got couple of lines of JavaScript using jQuery to resize images to thumbnails.
var thumb = $(this);
thumb.load(function() {
var ratio = thumb.height() / config.maxHeight;
var newWidth = Math.ceil(thumb.width() / ratio);
thumb.height(config.maxHeight);
// this line matters
thumb.width(newWidth);
});
Fotunately this works fine. But if I replace the last line with:
thumb.width(Math.ceil(thumb.width() / ratio));
It changes width of images that hasn't got explicitly defined dimensions badly (too narrow). To me, it seems like totally equivalent ways - via a variable or directly - but obviously they're not.
I tried casting the ceil() result to a Number or Integer and it behaved opposite way - images with undefined dimension were OK but the rest was too wide (width of original image).
Although I the first solution works I guess there's something fundamental I'm missing. So I want to avoid it in the future.
Thank you!
I would guess that the <img> element you are manipulating does not have declared height or width attributes. If that is the case, then the issue is how browsers intelligently resize images given only one constraint.
If you have an image that is 1000px wide, and 1000px tall, and you write an IMG tag like this:
<img src="big_image.gif" width="10" />
Modern browsers will render the huge image resized down to 10 by 10px.
So, on the line where you alter the height:
thumb.height(config.maxHeight);
the browser goes ahead an also alters the width. If you subsequently read the width (i.e. thumb.width(Math.ceil(thumb.width() / ratio))), you are going to be reading the new width, not the width it had before being given a new height.
var someImg = new Image();
someImg.src = <theURLofDesiredImage>
alert(someImg.width + " : " + someImg.height);
This is not Jquery but its vanilla JS and its a true way to determine "an unloaded" (not cached!) image. Add a query string to the URL url + "?asdasdasdadads" will allow you to circumvent the browser caching the image. This will result in a longer "image load time" but you will ALWAYS and more importantly, PREDICTABLY, resolve the dynamically loaded image.
Hi I am currently working on a script given to me by my boss and it is not working in all browsers except IE.
Now he is using the CSS property left to animate it so he has a variable which gets the current value of left. For example lets say left is equal to -100px.
Now once it has this value it adds 10px onto the value to make it move in from the left.
Now my issue lies with parseInt() and the "px" prefix at the end of the number. it keeps returning NaN instead of the value of left.
Does anyone know how to fix this problem?
Thanks in advance
UPDATE:
Ok I have rewritten the code and it can be viewed here, by re-written I mean I have took my bosses code and changed variable names and commented it to make it easier to understand and see what it trying to be accomplished with the javascript.
Now the slider is meant to make he selected DIV slide in from the left and into place (the DIV is offet by -760px) in IE this works fine, but not in any other browser. I have however come up with a fix in a way for the other browsers. by removing the px in the stylesheet from the end of -760 it causes the DIV to appear but it does not slide in how it should.
To make it easier im going to supply the sliders html and CSS for them here to hpefully help a little.
The HTML
The CSS
try catch
try{
w=parseInt(document.getElementById("slideDiv").style.left+"make me string");
}catch(e){
w=0;
alert(e.toString());
}
You might try something like this:
// should return e.g. "10px":
var valueAsString = document.getElementById('slideDiv').style.left;
// remove "px" at the end, so w will only contain "10":
numericPartOfValue = value.substring(0, value.length - 2);
var w = parseInt(numericPartOfValue);
if(w < 0) {
w = w+10;
// Note: Updated after the comment below:
document.getElementById(slideDiv).style.left =w + "px";
}
Use parseFloat instead of parseInt
I get this problem in IE7 when running a piece of code that uses jquery and 2 jquery plugins. The code works in FF3 and Chrome.
The full error is:
Line: 33
Char: 6
Error: bg is null or not an object
Code: 0
URL: http://localhost/index2.html
However line 33 is a blank line.
I am using 2 plugins: draggable and zoom. No matter what I do to the code it is always line 33 that is at fault. I check the source has update via view source but I feel this could be lying to me.
<body>
<div id="zoom" class="zoom"></div>
<div id="draggable" class="main_internal"><img src="tiles/mapSpain-smaller.jpg" alt=""></div>
<script type="text/javascript">
$(document).ready(function() {
$('#draggable').drag();
$('#zoom').zoom({target_div:"draggable", zoom_images:new Array('tiles/mapSpain-smaller.jpg', 'tiles/mapSpain.jpg') });
});
</script>
</body>
Essentially what I am trying to do is recreate the Pragmatic Ajax map demo with jQuery.
It would appear that the second line of this snippet is causing the trouble:
bg = $(this).css('background-position');
if(bg.indexOf('%')>1){
It seems to be trying to select the background-position property of #draggable and not finding it? Manually adding a background-position: 0 0; didn't fix it. Any ideas on how to get around this problem?
I tried using the MS Script Debugger but that is nearly useless. Can't inspect variables or anything else.
A bit more digging about on the Interweb has revealed the answer: IE doesn't understand the selector background-position. It understands the non-standard background-position-x and background-position-y.
Currently hacking something together to workaround it.
Nice one, Redmond.
To get around the fact that Internet Explorer does not support the "background-position" CSS attribute, as of jQuery 1.4.3+ you can use the .cssHooks object to normalize this attribute between browsers.
To save yourself some time, there is a background position jQuery plugin available that allows both "background-position" and "background-position-x/y" to work as expected in browsers that don't support one or the other by default.
It is interesting. IE8 doesn't understand getter backgroundPosition, but it understands setter.
$('.promo3').mousewheel(function(e,d){
var promo3 = $(this);
var p = promo3.css('backgroundPosition');
if (p === undefined) {
p = promo3.css('backgroundPositionX') + ' ' + promo3.css('backgroundPositionY');
}
var a = p.split(' ');
var y = parseInt(a[1]);
if (d > 0) {
if (y < -1107) y += 1107;
y -= 40;
}
else {
if (y > 1107) y -= 1107;
y += 40;
}
promo3.css('backgroundPosition', a[0] + ' ' + y + 'px');
return false;
});
It works great in IE8 and IE8 compatible view.
This worked for me:
if (navigator.appName=='Microsoft Internet Explorer')
{
bg = $(drag_div).css('backgroundPositionX') + " " + $(drag_div).css('backgroundPositionY');
}
else
{
bg = $(drag_div).css('background-position');
}
hope it does for you.
You may want to check to make sure that you are loading your js files in the correct order so that any dependencies are taken into account.
A bit of thinking (and a cup of tea) later I came up with:
if(bg == 'undefined' || bg == null){
bg = $(this).css('background-position-x') + " " + $(this).css('background-position-y');
}
Unfortunately it returns center center despite the online resources I can find state it should return 0 0 if the values are undefined.
Beginning to wonder if there is an actual fix/workaround to this. A lot of people have tried and all so far fail to catch all edge cases.
The camelCase version of backgroundPosition seems viable but I don't know enough of jQuery to make an accurate assessment of how to go about it - from what I have read you can only use camelCase as getters if the property has been set previously. Please tell me if I am mistaken.
However line 33 is a blank line.
It'll be line 33 of one of your .js files, not line 33 of the HTML itself. IE fails to report which actual file the error was in. Look at line 33 of each .js for something about ‘bg’; if the worst comes to the worst you can start inserting newlines at the start of each .js and see whether the line number changes.
I check the source has update via view source but I feel this could be lying to me.
View source will always show you what IE got from the server. It won't show any updates to the DOM.
try backgroundPosition istead
Also, make sure that 'this' exists and that your request for an attribute returns a value. IE will throw this kind of errors when you try to call a method on a property that does not exist, therefore bg is null or null an object. if you dont care about IE you can do bg = $(this)... || '' so that theres always something referenced.
Also, unrelated to the error you're getting, but is your index value of 1 correct? Did you mean -1 ?
Yupp, Try background-position instead or just set the background-position with jquery before you call it. Ill guess one often knows the positions through CSS before calling it. It isnt pretty, but somehow it did the trick for me.)
eg:
//set it in with javascript.
$("someid").css("background-position", "10px 0");
...
//do some funky stuff
//call it
$("someid").css("background-position");
//and it would return "10px 0" even in IE7
if nothing helps, it's also possible to make the following trick.
We can replace a background of an element by an inner absolutely positioned element (with the same background). The coordinates will be replaced by left and top properties. This will work in all browsers.
For better understanding, please, check the code:
Before
<div></div>
div {
background: url(mySprite.png);
background-position: -100px 0;
}
After
<div>
<span></span>
</div>
div {
position: relative;
overflow: hidden;
width: 100px; /* required width to show a part of your sprite */
height: 100px; /* required height ... */
}
div span {
position: absolute;
left: -100px; /* bg left position */
top: 0; /* bg top position */
display: block;
width: 500px; /* full sprite width */
height: 500px; /* full sprite height */
background: url(mySprite.png);
}
This solution is not very flexible, but it helped me to show icons hover state properly.
You can't use dashes in the jquery css function. You have to do it in camelCase:
.css('backgroundPosition') or .css('backgroundPositionX') and .css('backgroundPositionY') for IE