Resize video embeds on Tumblr blog with JavaScript - javascript

I have a Tumblr theme with responsive design enabled, and want to resize video iframes. Here is a sample of how the page's HTML might look like:
/* rest of blog */
<div id="box-content">
/* other posts; may contain more video posts */
<div class="post video">
<iframe src="[REDACTED]"
style="display:block;background-color:transparent;overflow:hidden"
class="embed_iframe tumblr_video_iframe"
scrolling="no" frameborder="0"
data-can-gutter="" data-can-resize=""
data-width="500" data-height="500"
width="500" height="500" allowfullscreen=""
mozallowfullscreen="" webkitallowfullscreen="">
</iframe>
<div class="post-content">
/* post content */
</div>
</div>
/* other posts; may contain more video posts */
</div>
/* rest of blog */
I have this function that (I think; I never really learned JavaScript) stores the original width and height of the iframe, as well as the width of the parent, in variables, and changes the width and height of the iframe.
My intended method was
Get all the elements with the class "video"
There is a child iframe element for each of them. Store each of the following in its variable:
a. that iframe's original width (ow),
b. that iframe's original height (oh), and
c. the parent element's width (cw for container width)
Set the iframe's width to cw.
Set the iframe's height to oh * cw / ow. (Explanation: cw / ow calculates the scaling factor to maintain the aspect ratio of the iframe.)
Run the function once on load.
Set an event listener for window resize.
...and the function that didn't work was:
function resizeVideos() {
var videoPostNodeList = document.getElementsByClassName("video");
for (var i = 0; i < videoPostNodeList.length; i++) {
var videoNode = videoPostNodelist[i].getElementsByTagName("iframe")[0];
var ow = videoNode.offsetWidth;
var oh = videoNode.offsetHeight;
var cw = videoPostNodelist[i].offsetWidth;
videoNode.offsetWidth = cw;
videoNode.offsetHeight = oh * cw / ow;
}
}
resizeVideos();
window.addEventListener("resize", resizeVideos);
The current version of this theme is available at testing-html.tumblr.com, on which I currently have three videos reblogged: one square video, one horizontal widescreen video, and one vertical widescreen video. What amateur mistake did I make with this?

An element's offsetWidth and offsetHeight are measurements of what's visible, including the element's borders, padding, scrollbar (if present & rendered) and CSS width.
You do have other options though, like clientWidth and clientHeight
and scrollWidth and scrollHeight (which unfortunately doesn't have a good image on MDN)
Based on your description of what you want, I'd say you should set your ow and oh based on the scrollWidth and scrollHeight properties instead.
All of these properties are read-only, so you can't just set them directly.
If I understand the situation correctly, your best bet is likely to be setting the elements max-width and max-height CSS properties (though you may prefer to directly override width and height):
function resizeVideos() {
var videoPostNodeList = document.getElementsByClassName("video");
for (var i = 0; i < videoPostNodeList.length; i++) {
var videoNode = videoPostNodelist[i].getElementsByTagName("iframe")[0];
var ow = videoNode.scrollWidth;
var oh = videoNode.scrollHeight;
var cw = videoPostNodelist[i].offsetWidth;
videoNode.style.maxWidth = cw;
videoNode.style.maxHeight = oh * cw / ow;
}
}
Finally, wait till the content is loaded before you run it (and as you did before, run it on window resize too):
document.addEventListener("DOMContentLoaded", resizeVideos);
window.addEventListener("resize", resizeVideos);
See Determining the dimensions of elements on MDN for more info.

Related

How to redesign ionic app layout so it looks good on all devices?

For example I want to set the height of a button or a header and make it 20% of the devices's vertical viewport. I can go and change it in the CSS file. But that doesn't take different screensizes into account. For example setting the attribute "height" of that button (or any other element) to 20%, but that means it is 20% of it's parent element, but not the height of the screen size of a given device. I can set it to a specific value in px. But that means the button's height is fixed.
I could do it with viewport: vh, vw.
.myButton {
height: .2vh;
}
But this is not supported on older devices (~Android 4.4). I'm thinking of doing it with vanilla JavaScript:
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
viewPortWidth = w.innerWidth || e.clientWidth || g.clientWidth,
viewPortHeigth = w.innerHeight|| e.clientHeight|| g.clientHeight;
button.height = viewPortHeigth * .2 + "px";// height of button will be dependent on device's viewport height
But I wonder whether there is another method that is recommended by experienced developers or the ionic team.
How can I set certain elements to a certain value relative to the device's size.
What worked best for me was media-queries.
For more information about this topic and more alternatives see here:
https://forum.ionicframework.com/t/support-for-various-mobile-devices-ios-android-phones-tablets-how-to-manage/17406

Get XY coords & Height/Width of div background image, when using background-size:contain

I'm designing a web page that has a photo for a background image of the main page.
The image must cover as much of the available window size as possible, whilst maintaining the correct aspect ratio.
To that end, I have a "container" div with the following CSS:
div.background {
background-image: url('/Content/Images/Home/main-bg.png');
background-repeat:no-repeat;
background-size:contain;
background-position:center;
float:left;
width:100%;
}
which is working perfectly.
However, I now need to position additional dom elements at specific places on the image, which are also scaled to the same as background image.
I initially thought that using JQuery and reading the "background-image-x","background-image-y", "background-image-x", "background-position-x", and "background-position-y" CSS properties might give me the information I need to position the additional elements.
However, these are not returning the needed information (for example, image-x and image-y both return "50%").
Is there some nice and simple(ish) way to achieve what I need... or am I going to have to resort to using Javascript and math to manually set the position and size of the background image (thus giving me the answers I need)?
I hate math. Please don't make me use it :)
You could work this out with some quite simple comparative ratios, of the image width vs image height compared to container width vs container height. To work out whether the image will be scaled horizontally or vertically.
img_ratio = img_width / img_height;
container_ratio = $(elm).width() / $(elm).height();
Following that you can work out the offset quite simply as you can work out by what percentage the image has been scaled. And apply that to the opposite mesasurement, and compare it to the container.
if(container_ratio > img_ratio){
//centered x height 100%
var scale_percent = $(elm).height() / img_height;
var scaled_width = img_width * scale_percent;
var x_offset = ($(elm).width() - scaled_width) / 2;
offset = [x_offset, 0];
}else{
//centered y width 100%
var scale_percent = $(elm).width() / img_width;
var scaled_height = img_height * scale_percent;
var y_offset = ($(elm).height() - scaled_height) / 2;
offset = [0, y_offset];
}
I've wrapped this up in an example fiddle at: http://jsfiddle.net/y2LE4/
I hope to help.
Try with:
$(document).ready(function(){
var something = background.offset();
}
or
$(document).ready(function(){
var something = $('.background').outerWidth(true);
}
Or just the width feature: http://api.jquery.com/width/

Javascript function to find total page height

I'm after a simple javascript function that will detect the total height of my web page which is dynamic and apply it to the height of a div which is the page background. Would it be possible to implement it?
The div is called bg...
Any ideas? Thanks in advance
Try:
var height = body.offsetHeight ? body.offsetHeight : html.offsetHeight;
document.getElementById ('divID').style.height = height + 'px';
Here an useful documentation:
http://www.quirksmode.org/dom/w3c_cssom.html
Im using currently following code to do that:
var getBodyHeight = function () {
var d = document,
bd = d.body,
dd = d.documentElement,
max = Math.max(
bd.scrollHeight,
bd.offsetHeight,
bd.clientHeight,
dd.offsetHeight,
dd.scrollHeight,
dd.clientHeight
);
return max;
};
This is what I use to figure out the height of content in iFrame for the purpose of adjusting it properly.
var body = document.body,
html = document.documentElement,
height = 0;
height = body.offsetHeight;
if(height === 0){
height = html.offsetHeight;
}
The reason for checking the body first is that the height of html is actually the height of the iFrame, which could be bigger than the content itself. However, in certain cases such as when body has no height, then it falls back to use height of html instead.
For your case, you might want to experiment with a similar scheme. I'm not sure why you have to use a div to set background so I can't really suggest a better alternative (if any).
Solution based on the comment below:
What you can do is the following. Have a div inside the main container with position absolute, width/height 100% and z-index -1. Then it will always be the correct size no matter how large the contain grow or shrink. With this approach, you will have to make sure that container always has size. This is a pure CSS solution, which might be simpler than using Javascript to adjust.
var height = screen.height;
var width = screen.width;
var resolution = width+"x"+height;
alert(resolution);
it gives the resolution of the screen.i know you want page height and width but it will help you later in web development. i am using it as most important part for my web!

Font size to fill dynamic div

I'm trying to get font size to adjust to fill a container. This alone obviously is not an issue. However, the container is also not a static size, it's size is set to a % of the browser window and I would like the font size to dynamically update on browser resizing, along with the container.
I had been using a modified script that I found which adjusts the font size by a % of the browser height and width.
$( document ).ready( function() {
var $body = $('body'); //Cache this for performance
var setBodyScale = function() {
var scaleFactor = 0.0001,
scaleSource = $(window).height(),
scaleSource2 = $(window).width(),
maxScale = 200,
minScale = 10;
var fontSize = (scaleSource * scaleSource2) * scaleFactor; //Multiply the width of the body by the scaling factor:
if (fontSize > maxScale) fontSize = maxScale;
if (fontSize < minScale) fontSize = minScale; //Enforce the minimum and maximums
$('body').css('font-size', fontSize + '%');
}
$(window).resize(function(){
setBodyScale();
});
//Fire it when the page first loads:
setBodyScale();
});
I wasnt getting the desired result from this, so then tried changing this so that the scale sources were the container rather than the window. This somewhat worked however it didnt dynamically update, it would require a refresh of the page.
In short I cannot find a way to resize font size, to fill a container that's size is determined by a % of the browser window, on the fly.
Why invent something that already exists? There's already a great jQuery tool out there: http://fittextjs.com/
This isn't a real-world answer, yet, but viewport dependent font sizes are on the horizon:
http://css-tricks.com/viewport-sized-typography/
Currently it's only supported in Chrome Canary, but it's good to know it's coming.

CSS/Javascript fluid font size

My application has two views, a live mode and a preview mode. Both of these have windows which can be resized. They are the same html file. I am looking for a way to get the font-size to resize proportionally for both views when they are resized.
I am using jQuery as my javascript framework.
Is there a way of getting this to work in either CSS or jQuery?
I know I am answering my own question, but the answer above was helpful but not enough to suffice as one. So this is how I ended up doing it.
First I set up this function which calculates a suitable font size based on a given width.
function getFontSize(width){
sizew = width / 100;
size = sizew * 1.5;
return size;
};
Then I got the function to run on load and on re size of the window then modify the body font size accordingly.
$(window).resize(function(){
size = getFontSize($(this).width());
$("body").css("font-size", size + "px");
}).resize();
All you have to do from there is set up any element to have its font-size re-sizable by giving it an "em" or percentage font size.
Sure, define a javascript object which has a function that takes in a width and height parameter. It should return your desired font size based on that width and height. Then, attach a resize event handler to your window, which calls that function you just defined and sets the font-size css property on the document body of the window.
You must use this plugin to get a resize event on an html element that is not the window: http://benalman.com/projects/jquery-resize-plugin/
var fontsize = function FontSizeBasedOnDimensions{
var that = {};
that.GetFontSize = function(height, width){
//Make some decisions here
}
return that;
}();
$('#yourwindow').resize(function(){
var size = fontsize.GetFontSize($(this).css('height'), $(this).css('width'));
var currentsize = parseInt($(this).css('font-size'),10);
if(size != currentsize){
$(this).css('font-size', size);
}
});

Categories