Videojs get video dimensions in fullscreen mode - javascript

I am able to get the width & size of the actual video (not the player) when not in fullscreen mode using the videoWidth() and videoHeight(), like this:
var SVideo = videojs('SingularVideo').ready(function(){
resizeFunc(this.videoWidth(), this.videoHeight())
});
The problem is that I need to check the video size when the user enters fullscreen mode, so I listen on the "fullscreenchange" event and check again:
SVideo.on("fullscreenchange",
function () {
resizeFunc(SVideo.videoWidth(), SVideo.videoHeight());
});
But in the fullscreenchange callback, the width and height don't change, the values are the same as if the video is not in fullscreen mode.
I would very much appreciate any suggestions as how to get the actual video width and height when in fullscreen mode. TIA!

I was looking for the video-dimensions, but not in fullscreen mode. I can see this is an old question, - so you probably don't have the issue still. But hopefully, it can help someone else.
I did find this in the documentation: currentDimensions ... However... I was hoping to get the aspect ratio of the video, - and not the size of the video-element (including the black edges/borders/fillers). I did figure out, that if I set fluid to true ( the fluid option ), then the video would take up the entire video-HTML-element.
Please note, that the fluid-option is implemented slightly after the video is rendered, - so I had to use setTimeout (uuuuuugly!), to get the correct aspectRatio.
Here is my (VueJS)-code:
mounted() {
this.player = videojs(this.$refs.videoPlayer, this.videoOptions, () => {
this.calcAspectRatio();
this.setMaxWidth();
setTimeout( () => {
this.calcAspectRatio();
this.setMaxWidth();
});
setTimeout( () => {
this.calcAspectRatio();
this.setMaxWidth();
}, 1000 );
setTimeout( () => {
this.calcAspectRatio();
this.setMaxWidth();
}, 2000 );
});
}
methods: {
calcAspectRatio(){
if( this.player && this.player.currentDimensions( 'width' ).width ){
this.aspectRatio = this.player.currentDimensions( 'width' ).height / this.player.currentDimensions( 'width' ).width;
}
},
setMaxWidth(){
let maxWidth = 1 / this.aspectRatio * ( ( this.VIEWPORTHEIGHTWHICHISCALCULATEDELSEWHERE - 100 ) * 0.90 );
document.querySelector( '#' + this.id ).style.maxWidth = maxWidth + 'px';
},
}

Since it is on full screen, you can get the width and height of the screen using the code below:
var width = screen.width;
var height = screen.height;

Related

Mobile screen/viewport size detection - Javascript

I want to report the screen size of a mobile device and update on orientation change but am getting all sorts of strange errors e.g. width almost always 980px.
This works fine on desktop when resizing but not mobile (reporting landscape or portrait is fine though)
Tried on ipad, samsung galaxy tab, google nexus phone and iphone 4
Here's what I'm using:
// get dimensions
_getScreenWidth = function() {
var screenWidth = window.innerWidth;
var screenHeight = window.innerHeight;
var el = document.getElementById('dimensions');
_handleOrientation();
el.innerHTML = 'Width: '+screenWidth +' :: Height: '+screenHeight + "<br /><br />" + _doc_element.className;
};
// portait or landscape
_handleOrientation = function() {
if (device.landscape()) {
_removeClass("portrait");
return _addClass("landscape");
} else {
_removeClass("landscape");
return _addClass("portrait");
}
};
// resize event
var resizeTimeout;
window.onresize = function() {
clearTimeout(resizeTimeout);
// handle normal resize
resizeTimeout = setTimeout(function() {
_getScreenWidth();
}, 250); // 250ms delay
}
You will not get width in physical pixels. Instead, you'll receive "CSS pixels". This is why you getting strange errors. For orientation detecting, you can use "CSS pixels", just compare width to height.
I'm not sure what device.landscape() is supposed to be, but the device object doesn't exist, at least not in standard browsers.
all sorts of strange errors
In my case, that was due to undefined _addClass and _removeClass functions, _doc_element object and as mentioned above, device.landscape().
To fix device.landscape(), you can define landscape as a mode where width > height. Then it's just a simple comparison:
isLandscape = function() {
return window.innerWidth > window.innerHeight;
}
Here is example on jsfiddle with all of the errors fixed. Tested on iPhone 6 and it's setting correct classes.

Fluid sliding panel : make it work on load and after resize with computed values?

I'm trying to put together a fluid sliding panel which should take into account the inner width of the window on load, as well as on resizes : depending on the actual window size, the panel should be moved left / right a fourth of the window width.
So far i managed to bypass the multiple resize events happening when the user resizes the window, thx to this thread.
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = "Don't call this twice without a uniqueId";
}
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
var slidinNav = function(rtr){
document.getElementById('navPanel').style.left = -rtr + "px";
document.getElementById('navPanel').style.width = rtr + "px";
$('.showMenu').click(function(){
$('#navPanel').animate({left: '+=' + rtr +'px'}, 400);
});
$('.hideMenu').click(function(){
$('#navPanel').animate({left: '-=' + rtr + 'px'}, 400);
});
}
$(document).ready(function(){
var winW = window.innerWidth;
var navPosLeft=winW/4;
slidinNav(navPosLeft);
});
$(window).resize(function () {
waitForFinalEvent(function(){
var winW = window.innerWidth;
var navPosLeft=winW/4;
slidinNav(navPosLeft);
console.log(" Left / Width : " + navPosLeft);
}, 200, "un identifiant unique ?");
});
But being a complete javascript newbie i haven't found the solution to prevent the variables i use to store the window width value and offset to take all the successive values computed.
Better than a long and unclear explanation see jsfiddle here.
Here's my question : Should i reset variables (how and when) or rather try and get the last value (and again : how and when) ?
Thx for any help on this one ; - )
Correct me if I am not understanding exactly what you are looking for here but it looks to me like you may be making it more complicated than it needs to be.
Looks like you could simply just stay with using % and just have these functions:
$('.showMenu').click(function(){
$('#navPanel').animate({left: 0}, 400);
});
$('.hideMenu').click(function(){
$('#navPanel').animate({left: "-20%"}, 400);
});
As demonstrated here: http://jsfiddle.net/X9Jrc/3/

Detect vertical resize jquery

I am making a login page in which I use a little javascript and jquery to vertically align the login box.
I also have an event on resize() to put the box in the middle again.
But, with resize(), everytime the user resize the window, the function is fired and this is a kind of ugly :))
So, I would like to know if there is a way to fire the function only on vertical resize.
Thank you
It will fire every time, but you can track the width to check for only vertical resizing:
// track width, set to window width
var width = $(window).width();
// fire on window resize
$(window).resize(function() {
// do nothing if the width is the same
if ($(window).width()==width) return;
// update new width value
width = $(window).width();
// ... your code
});
Instead of comparing heights for each situation where you want to detect vertical resize, you can create reusable events for horizontal and vertical resizing like this:
// Horizontal and vertical window resize events.
(function () {
var win = jQuery(window),
prev_width = win.width(),
prev_height = win.height();
win.on('resize', function () {
var width = win.width(),
height = win.height();
if (width !== prev_width) {
win.trigger('hresize');
}
if (height !== prev_height) {
win.trigger('vresize');
}
prev_width = width;
prev_height = height;
});
})();
That way you can just drop that code in place once, and then use the events like this:
$(window).on('hresize', function () {
// handle horizontal resizing
});
$(window).on('vresize', function () {
// handle vertical resizing
});
Got better solution:
$('#element').resizable({
stop: function( event, ui ) {
$('#element').height(ui.originalSize.height);
}
});
As a complement to Doublesharp's useful answer:
In my case, window.outerWidth worked better, and was stable to vertical resizes.
Indeed, I had some troubles with $(window).width() : it (strangely!) happened to be modified also when I only resized vertically.

Making a set of images move cross the screen then when leaving the window, it comes up from the other side

I'm trying to implement the marquee tag in jQuery by animation a set of images using animate() function, making them move to the right or left direction.
But, I couldn't figure out when a single image goes to the end of the screen returns individually to the other side.
Because I heard that the window size is not constant for every browser, So is there anyway to implement that?
this is what I came up so far(it's simple and basic):
$(document).ready(function(){
moveThumbs(500);
function moveThumbs(speed){
$('.thumbnails').animate({
right:"+=150"
}, speed);
setTimeout(moveThumbs, speed);
}
});
note: I searched in SO for related questions, but had no luck to find exact information for my specific issue.
Here's a basic script that moves an image across the screen and then resumes on the other side and adapts to the window width.
You can see it working here: http://jsfiddle.net/jfriend00/rnWa2/
function startMoving(img) {
var img$ = $(img);
var imgWidth = img$.width();
var screenWidth = $(window).width();
var amount = screenWidth - (parseInt(img$.css("left"), 10) || 0);
// if already past right edge, reset to
// just left of left edge
if (amount <=0 ) {
img$.css("left", -imgWidth);
amount = screenWidth + imgWidth;
}
var moveRate = 300; // pixels per second to move
var time = amount * 1000 / moveRate;
img$.stop(true)
.animate({left: "+=" + amount}, time, "linear", function() {
// when animation finishes, start over
startMoving(this);
})
}
$(document).ready(function() {
// readjust if window changes size
$(window).resize(function() {
$(".mover").each(function() {
startMoving(this);
});
});
});
​ ​

Catch browser's "zoom" event in JavaScript

Is it possible to detect, using JavaScript, when the user changes the zoom in a page?
I simply want to catch a "zoom" event and respond to it (similar to window.onresize event).
Thanks.
There's no way to actively detect if there's a zoom. I found a good entry here on how you can attempt to implement it.
I’ve found two ways of detecting the
zoom level. One way to detect zoom
level changes relies on the fact that
percentage values are not zoomed. A
percentage value is relative to the
viewport width, and thus unaffected by
page zoom. If you insert two elements,
one with a position in percentages,
and one with the same position in
pixels, they’ll move apart when the
page is zoomed. Find the ratio between
the positions of both elements and
you’ve got the zoom level. See test
case.
http://web.archive.org/web/20080723161031/http://novemberborn.net/javascript/page-zoom-ff3
You could also do it using the tools of the above post. The problem is you're more or less making educated guesses on whether or not the page has zoomed. This will work better in some browsers than other.
There's no way to tell if the page is zoomed if they load your page while zoomed.
Lets define px_ratio as below:
px ratio = ratio of physical pixel to css px.
if any one zoom The Page, the viewport pxes (px is different from pixel ) reduces and should be fit to The screen so the ratio (physical pixel / CSS_px ) must get bigger.
but in window Resizing, screen size reduces as well as pxes. so the ratio will maintain.
zooming: trigger windows.resize event --> and change px_ratio
but
resizing: trigger windows.resize event --> doesn’t change px_ratio
//for zoom detection
px_ratio = window.devicePixelRatio || window.screen.availWidth / document.documentElement.clientWidth;
$(window).resize(function(){isZooming();});
function isZooming(){
var newPx_ratio = window.devicePixelRatio || window.screen.availWidth / document.documentElement.clientWidth;
if(newPx_ratio != px_ratio){
px_ratio = newPx_ratio;
console.log("zooming");
return true;
}else{
console.log("just resizing");
return false;
}
}
The key point is difference between CSS PX and Physical Pixel.
https://gist.github.com/abilogos/66aba96bb0fb27ab3ed4a13245817d1e
Good news everyone some people! Newer browsers will trigger a window resize event when the zoom is changed.
I'm using this piece of JavaScript to react to Zoom "events".
It polls the window width.
(As somewhat suggested on this page (which Ian Elliott linked to): http://novemberborn.net/javascript/page-zoom-ff3 [archive])
Tested with Chrome, Firefox 3.6 and Opera, not IE.
Regards, Magnus
var zoomListeners = [];
(function(){
// Poll the pixel width of the window; invoke zoom listeners
// if the width has been changed.
var lastWidth = 0;
function pollZoomFireEvent() {
var widthNow = jQuery(window).width();
if (lastWidth == widthNow) return;
lastWidth = widthNow;
// Length changed, user must have zoomed, invoke listeners.
for (i = zoomListeners.length - 1; i >= 0; --i) {
zoomListeners[i]();
}
}
setInterval(pollZoomFireEvent, 100);
})();
This works for me:
var deviceXDPI = screen.deviceXDPI;
setInterval(function(){
if(screen.deviceXDPI != deviceXDPI){
deviceXDPI = screen.deviceXDPI;
... there was a resize ...
}
}, 500);
It's only needed on IE8. All the other browsers naturally generate a resize event.
There is a nifty plugin built from yonran that can do the detection. Here is his previously answered question on StackOverflow. It works for most of the browsers. Application is as simple as this:
window.onresize = function onresize() {
var r = DetectZoom.ratios();
zoomLevel.innerHTML =
"Zoom level: " + r.zoom +
(r.zoom !== r.devicePxPerCssPx
? "; device to CSS pixel ratio: " + r.devicePxPerCssPx
: "");
}
Demo
Although this is a 9 yr old question, the problem persists!
I have been detecting resize while excluding zoom in a project, so I edited my code to make it work to detect both resize and zoom exclusive from one another. It works most of the time, so if most is good enough for your project, then this should be helpful! It detects zooming 100% of the time in what I've tested so far. The only issue is that if the user gets crazy (ie. spastically resizing the window) or the window lags it may fire as a zoom instead of a window resize.
It works by detecting a change in window.outerWidth or window.outerHeight as window resizing while detecting a change in window.innerWidth or window.innerHeight independent from window resizing as a zoom.
//init object to store window properties
var windowSize = {
w: window.outerWidth,
h: window.outerHeight,
iw: window.innerWidth,
ih: window.innerHeight
};
window.addEventListener("resize", function() {
//if window resizes
if (window.outerWidth !== windowSize.w || window.outerHeight !== windowSize.h) {
windowSize.w = window.outerWidth; // update object with current window properties
windowSize.h = window.outerHeight;
windowSize.iw = window.innerWidth;
windowSize.ih = window.innerHeight;
console.log("you're resizing"); //output
}
//if the window doesn't resize but the content inside does by + or - 5%
else if (window.innerWidth + window.innerWidth * .05 < windowSize.iw ||
window.innerWidth - window.innerWidth * .05 > windowSize.iw) {
console.log("you're zooming")
windowSize.iw = window.innerWidth;
}
}, false);
Note: My solution is like KajMagnus's, but this has worked better for me.
⬤ The resize event works on modern browsers by attaching the event on window, and then reading values of thebody, or other element with for example (.getBoundingClientRect()).
In some earlier browsers it was possible to register resize event
handlers on any HTML element. It is still possible to set onresize
attributes or use addEventListener() to set a handler on any element.
However, resize events are only fired on the window object (i.e.
returned by document.defaultView). Only handlers registered on the
window object will receive resize events.
⚠️ Do resize your tab, or zoom, to trigger this snippet:
window.addEventListener("resize", getSizes, false)
function getSizes(){
let body = document.body
body.width = window.innerWidth
body.height = window.innerHeight
console.log(body.width +"px x "+ body.height + "px")
}
getSizes()
⬤ An other modern alternative: the ResizeObserver API
Depending your layout, you can watch for resizing on a particular element.
This works well on «responsive» layouts, because the container box get resized when zooming.
function watchBoxchange(e){
info.textContent = e[0].contentBoxSize[0].inlineSize+" x "+e[0].contentBoxSize[0].blockSize + "px"
}
new ResizeObserver(watchBoxchange).observe(fluid)
#fluid {
width: 200px;
height:100px;
overflow: auto;
resize: both;
border: 3px black solid;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
font-size: 8vh
}
<div id="fluid">
<info id="info"></info>
</div>
💡 Be careful to not overload javascript tasks from user gestures events. Use requestAnimationFrame whenever you needs redraws.
I'd like to suggest an improvement to previous solution with tracking changes to window width. Instead of keeping your own array of event listeners you can use existing javascript event system and trigger your own event upon width change, and bind event handlers to it.
$(window).bind('myZoomEvent', function() { ... });
function pollZoomFireEvent()
{
if ( ... width changed ... ) {
$(window).trigger('myZoomEvent');
}
}
Throttle/debounce can help with reducing the rate of calls of your handler.
According to MDN, "matchMedia" is the proper way to do this https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#Monitoring_screen_resolution_or_zoom_level_changes
it's a bit finicky because each instance can only watch one MQ at a time, so if you're interested in any zoom level change you need to make a bunch of matchers.. but since the browser is in charge to emitting the events it's probably still more performant than polling, and you could throttle or debounce the callback or pin it to an animation frame or something - here's an implementation that seems pretty snappy, feel free to swap in _throttle or whatever if you're already depending on that.
Run the code snippet and zoom in and out in your browser, note the updated value in the markup - I only tested this in Firefox! lemme know if you see any issues.
const el = document.querySelector('#dppx')
if ('matchMedia' in window) {
function observeZoom(cb, opts) {
opts = {
// first pass for defaults - range and granularity to capture all the zoom levels in desktop firefox
ceiling: 3,
floor: 0.3,
granularity: 0.05,
...opts
}
const precision = `${opts.granularity}`.split('.')[1].length
let val = opts.floor
const vals = []
while (val <= opts.ceiling) {
vals.push(val)
val = parseFloat((val + opts.granularity).toFixed(precision))
}
// construct a number of mediamatchers and assign CB to all of them
const mqls = vals.map(v => matchMedia(`(min-resolution: ${v}dppx)`))
// poor person's throttle
const throttle = 3
let last = performance.now()
mqls.forEach(mql => mql.addListener(function() {
console.debug(this, arguments)
const now = performance.now()
if (now - last > throttle) {
cb()
last = now
}
}))
}
observeZoom(function() {
el.innerText = window.devicePixelRatio
})
} else {
el.innerText = 'unable to observe zoom level changes, matchMedia is not supported'
}
<div id='dppx'>--</div>
You can also get the text resize events, and the zoom factor by injecting a div containing at least a non-breakable space (possibly, hidden), and regularly checking its height. If the height changes, the text size has changed, (and you know how much - this also fires, incidentally, if the window gets zoomed in full-page mode, and you still will get the correct zoom factor, with the same height / height ratio).
<script>
var zoomv = function() {
if(topRightqs.style.width=='200px){
alert ("zoom");
}
};
zoomv();
</script>
On iOS 10 it is possible to add an event listener to the touchmove event and to detect, if the page is zoomed with the current event.
var prevZoomFactorX;
var prevZoomFactorY;
element.addEventListener("touchmove", (ev) => {
let zoomFactorX = document.documentElement.clientWidth / window.innerWidth;
let zoomFactorY = document.documentElement.clientHeight / window.innerHeight;
let pageHasZoom = !(zoomFactorX === 1 && zoomFactorY === 1);
if(pageHasZoom) {
// page is zoomed
if(zoomFactorX !== prevZoomFactorX || zoomFactorY !== prevZoomFactorY) {
// page is zoomed with this event
}
}
prevZoomFactorX = zoomFactorX;
prevZoomFactorY = zoomFactorY;
});
Here is a clean solution:
// polyfill window.devicePixelRatio for IE
if(!window.devicePixelRatio){
Object.defineProperty(window,'devicePixelRatio',{
enumerable: true,
configurable: true,
get:function(){
return screen.deviceXDPI/screen.logicalXDPI;
}
});
}
var oldValue=window.devicePixelRatio;
window.addEventListener('resize',function(e){
var newValue=window.devicePixelRatio;
if(newValue!==oldValue){
// TODO polyfill CustomEvent for IE
var event=new CustomEvent('devicepixelratiochange');
event.oldValue=oldValue;
event.newValue=newValue;
oldValue=newValue;
window.dispatchEvent(event);
}
});
window.addEventListener('devicepixelratiochange',function(e){
console.log('devicePixelRatio changed from '+e.oldValue+' to '+e.newValue);
});
Here is a native way (major frameworks cannot zoom in Chrome, because they dont supports passive event behaviour)
//For Google Chrome
document.addEventListener("mousewheel", event => {
console.log(`wheel`);
if(event.ctrlKey == true)
{
event.preventDefault();
if(event.deltaY > 0) {
console.log('Down');
}else {
console.log('Up');
}
}
}, { passive: false });
// For Mozilla Firefox
document.addEventListener("DOMMouseScroll", event => {
console.log(`wheel`);
if(event.ctrlKey == true)
{
event.preventDefault();
if(event.detail > 0) {
console.log('Down');
}else {
console.log('Up');
}
}
}, { passive: false });
I'am replying to a 3 year old link but I guess here's a more acceptable answer,
Create .css file as,
#media screen and (max-width: 1000px)
{
// things you want to trigger when the screen is zoomed
}
EG:-
#media screen and (max-width: 1000px)
{
.classname
{
font-size:10px;
}
}
The above code makes the size of the font '10px' when the screen is zoomed to approximately 125%. You can check for different zoom level by changing the value of '1000px'.

Categories