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");
Related
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);
I have a problem with height limitation of <div></div> in some web browsers, like Firefox. I have javascript code like this:
$('#MyDiv').css("height","20000000px"); // 20,000,000 pixel height
But I see height: 2e+7px; rule in the firebug. This problem exist in IE too, But in google chrome everything is ok and I see height: 20000000px;. How can I set very large value to div's height in a way that works for most browsers?
EDIT: firefox has no scrollbar in this div, but google chrome has scrollbar.
I want just confirm the problem which describes hamed. One can try the demo http://jsfiddle.net/OlegKi/y4tLxx53/4/ which contains setting height property using jQuery.css on the test div:
var testValues = [10000, 1533916, 1533917, 1533918, 10737418, 10737419,
17895696, 17895697, 17895698, 20000000], h, i;
for (i = 0; i < testValues.length; i++) {
h = testValues[i] + "px";
$("#test").css("height", h);
$("#log").append("<span>After setting height " + h +
", one have height: " + $("#test").css("height") +
"</span><br/>");
}
with very simple HTML markup
<div id="log"></div>
<div id="test"></div>
One can see in Google Chrome the expected results
but Firefox shows
and IE10 and IE11 displays
instead.
By the way, the setting of large height on divs will be used to implement "virtual scrolling" (for example in jqGrid). So that the user sees div with large scroll and a table inside. If the user uses scroll bar then the page of data will be downloaded from the server via Ajax. In the way the height of the div should corresponds to the size of data on the server. If one row of table data have height 23px, then IE10/IE11 can simulate in the simple way only 66692 rows of virtual data in IE (1533916/23=66692) and 778073 rows (less as a million rows) in Firefox. The demos shows that one need use more sophisticated implementation of "virtual scrolling" to have no, described above, problems with setting of height of div.
One can use the same inline demo alternatively:
var testValues = [10000, 1533916, 1533917, 1533918, 10737418, 10737419,
17895696, 17895697, 17895698, 20000000], h, i;
for (i = 0; i < testValues.length; i++) {
h = testValues[i] + "px";
$("#test").css("height", h);
$("#log").append("<span>After setting height " + h +
", one have height: " + $("#test").css("height") +
"</span><br/>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<div id="log"></div>
<div id="test"></div>
I have run into the same issue implementing virtual scrolling. My solution is to detect numbers that are too large and use a multiplier.
This means that the height of the overflowed content will be realHeight / multiplier. And when I'm trying to figure out what data to show, I just take the scrollTop * multiplier. This works fine to the user because the scrollbar has a minimum height.
This will work if you have control over the effect. I'm not familiar with jqGrid, but the source code may have to be updated.
That's not a problem. The value 2e+7 is the same as 20000000, it's just a different way of showing the number.
In some tools, large numbers are shown in scientific notation. The number 2e+7 means 2 * 107.
If your document is size is not fixed, you can use this:
var height = $(document).height();
and set your div container height accordingly
$('#MyDiv').css("height",height);
This should work on all the browsers
I'm trying to make a kind of "news bar" on a web page.
The bar use a CSS animation, and the text content is refreshed on each iteration using ajax to retrieve data from an RSS feed.
My problem is that the content length may vary, so I want to set the size of the font used to display the text small enough to display all the content.
I then use this function to resize the text content:
function resize(content /*content div*/, maxHeight/*bar height*/, maxWidth /*bar width*/) {
content.parentNode.style.fontSize = maxHeight + 'px';
var totalwidth = content.offsetWidth;
if (totalwidth > maxWidth) {
content.parentNode.style.fontSize = (maxHeight * maxWidth / totalwidth) + 'px';
}
}
It sometimes works on first iteration, but after it returns totally wrong values (like 36) for totalWidth.
If I put a breakpoint on the 'if' line the debugger display a coherent value (like 4320) for content.offsetWidth.
How can I fix this ?
I've found the solution.
I have to set the content as "inline-block".
If content display is set as "block" its offsetWidth vary with the css animation.
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.
Thanks for looking into this.
Basically, what I am trying to do is to get the height of a div (which is set to 100% in my style.css, so it should be resizable on any device hopefully) so that I could print numbers 1-whatever number.
So for example if the window is small it'd print out the numbers 1-45, if it's a smartphone browser, then the numbers will scale down to 1-10.
at the moment that's what it looks like:
<div id="line_numbers">
<script type="text/javascript">
var i=0;
var div_height=(document.getElementById('line_numbers').offsetHeight)/ getElementsByTagName("p").style.fontSize();
while (i < div_height) { //if i is less that the height
i++; //then increase its number
document.write("<p>" + i + "</p>"); //and print out the number and new line (<p>)
}
</script><!--end of iteration script-->
</div><!--end of line numbers-->
I understand the height var calculation is wrong but I hope you understand the logic: Got the height of the div and given that padding for every (every printed number) is 5px and the height of the font of every number, I can divide the height by the font size+10px (upper and lower padding).
When I try to print out the div_height variable nothing happens and I am a bit confused.
Thank you for taking time, again.
blagie-bla
It looks like you got what you came for, but here's a heads-up to supplement the answers above: Consider using element.style.lineHeight instead of element.style.fontSize, as only the former multiplied by the number of lines will give you the actual height of the div, (or an accurate line-count given height \ line-height).