I'm new to jQuery and i'm still in the process of learning HTML and CSS. I wanted to have a responsive image on the homepage of my website that scaled itself with the user's browser window. I found this at github: https://github.com/gutierrezalex/photo-resize.git
but i think i might be using it wrong, since i can't get it to work for me.
Here's my html:
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
</script>
<reference path="jquery-1.5.1.min.js" />
<script src="jquery-photo-resize.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("img").photoResize()
});
</script>
</head>
and here's the jquery-photo-resize.js file:
function photoResize($) {
"use strict";
$.fn.photoResize = function (options) {
var element = $(this),
defaults = {
bottomSpacing: 10
};
function updatePhotoHeight() {
var o = options,
photoHeight = $(window).height();
$(element).attr('height', photoHeight - o.bottomSpacing);
}
$(element).load(function () {
updatePhotoHeight();
$(window).bind('resize', function () {
updatePhotoHeight();
});
});
options = $.extend(defaults, options);
};
}
Like i said, i'm a novice, so please let me know what i'm doing wrong, and how i can achieve my desired effect.
You don't need jquery for this. Just set a class name and then in your style sheet use a width. If you only set a width it'll auto size the height to maintain the aspect ratio. Same goes for setting the height only. If you set both your aspect ratio may be off. The width can be a percentage of the current element. You could also use vw (view port width). Also calc is super helpful.
{ width:75%}
Update:
.cropper {
width: 75px;
height: 75px;
overflow: hidden;
position: relative;
}
.cropped {
width: 100px;
position: absolute;
left: -12.5px;
top: -12.5px;
}
<div class="cropper">
<img class="cropped" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/SIPI_Jelly_Beans_4.1.07.tiff/lossy-page1-256px-SIPI_Jelly_Beans_4.1.07.tiff.jpg"/>
</div>
Here is code :
CSS :
.featured { overflow:hidden;
border:2px solid #000;
position:relative;}
.featured img { width:100%; position:relative;}
#pos_1 { width:200px; height:190px; }
#pos_2 { width:150px; height:250px; }
#pos_3 { width:350px; height:150px; }
HTML :
<div id="topGallery">
<article class="featured" id="pos_1">
<img src="abc.jpd" class="attachment-post-thumbnail wp-post-image" alt="piano" />
</article>
</div>
Javascript :
jQuery(document).ready(function($) {
///HOME PAGE - image resizing
function imageLoaded() {
var w = $(this).width();
var h = $(this).height();
var parentW = $(this).parent().width();
var parentH = $(this).parent().height();
//console.log(w + '-' + h + '-' + parentW + '-' + parentH);
//if (w >= parentW){ //always true because of CSS
if (h > parentH){
$(this).css('top', -(h-parentH)/2);
} else if (h < parentH){
$(this).css('height', parentH).css('width', 'auto');
$(this).css('left', -($(this).width()-parentW)/2);
}
//}
}
$('#topGallery img').each(function() {
if( this.complete ) {
imageLoaded.call( this );
} else {
$(this).one('load', imageLoaded);
}
});
});
Related
Here is some Javascript and CSS from my program:
<script>
var $body = $('body');
$body.waypoint(function (direction) {
if (direction == 'down') {
$body.addClass('body2');
} else{
$body.removeClass('body2');
}
}, { offset: '50%'});
</script>
<style>
body {
background-image: url("images/image1.png");
background-repeat: no-repeat;
background-position: 400px 200px;
background-size: 900px 300px;
margin-right: 400px;
background-attachment: fixed;
}
.body2 {
background-image: url("images/image2.png");
background-repeat: no-repeat;
background-position: 400px 200px;
background-size: 900px 300px;
margin-right: 400px;
background-attachment: fixed;
}
I'm trying to change the background image from image1 (body) to image2 (body2) as I scroll 50% of the way down the page. However, when I launch the program the only image displayed is image2 and nothing changes as I scroll. Any help would be greatly appreciated, thanks in advance!
I tried to use waypoints, but I can't seem to make it work though (it gives unreliable results for me, on Chrome).
You could use your own custom function to handle the scroll event as you wish.
You need to compute:
height: total document height (offset 50% = height/2)
y: current scroll position
direction: by comparing y with the last scroll position
Like in this example (Run code snippet):
/**
* very simple on scroll event handler
* use: Scroller.onScroll(..custom function here...)
* custom function gets 3 parameters: y, height and direction
*/
var Scroller = {
_initiated: 0,
_init: function() {
var t = this;
t._listener = function() {
t._scrollEvent();
};
window.addEventListener("scroll", t._listener);
t.y = t.getY();
t._initiated = 1;
},
_onScroll: null,
_scrollEvent: function() {
var t = this;
if (!t._initiated || !t._onScroll)
return false;
var y = t.getY();
t.height = document.body.scrollHeight;
t.direction = y < t.y ? "up" : "down";
t.y = y;
t._onScroll(t.y, t.height, t.direction);
},
getY: function() {
//for cross-browser compatability
// https://stackoverflow.com/a/51933072/4902724
return (window.pageYOffset !== undefined) ?
window.pageYOffset :
(document.documentElement || document.body.parentNode || document.body).scrollTop;
},
onScroll: function(fn) {
var t = this;
t._onScroll = fn;
if (!t._initiated)
t._init();
},
destroy: function() {
var t = this;
window.removeEventListener("scroll", t._listener);
t._onScroll = null;
t._initiated = 0;
}
};
/**
* global vars
*/
var $body = $("body");
// keep track of changes, to cancel unnecessary class changes
$body.classChanged = 0;
/**
* on scroll setup
*/
Scroller.onScroll(function(y, height, direction) {
/* to check for 50%, compare y vs. height/2 */
if (y > height / 2 && direction == "down" && !$body.classChanged) {
$body.addClass("body2");
$body.classChanged = 1;
}
if (y < height / 2 && direction == "up" && $body.classChanged) {
$body.removeClass("body2");
$body.classChanged = 0;
}
});
body {
background-color: lightgreen;
}
.body2 {
background-color: gold;
}
/* demo helpers...*/
div {
float: left;
width: 100%;
height: 250px;
border: 1px solid grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Sroll down below 50% to change body color...."</p>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
Hope this helps, even without that plugin.
I've actually figured out the problem. All I needed to do was set the offset percentage as negative.
Basically what I am trying to do is have images fill a div whilst maintaining their aspect ratio. So I am using jquery to identify whether they are portrait or landscape, and set either width or height from there.
My problem is the code gives all the images landscape class. I am at my wits end to know why...
Thank you!
HTML
<div class="prop">
<div class="propimage"><img src="{#image}" alt="{#prop_name}"></div>
<div class="propname">{#prop_name}</div>
<div class="propdescription">{#description}</div>
<div class="propprice">{#price}</div>
</div>
CSS
.portrait img {
width: 100%;
}
.landscape img {
height: 100%;
}
.propimage img {
display: block;
}
img {
max-width: none;
}
.propimage {
width: 100%;
height: 300px;
overflow: hidden;
float: left;
}
SCRIPT
<script>
$(".propimage").each(function(){
// Uncomment the following if you need to make this dynamic
//var refH = $(this).height();
//var refW = $(this).width();
//var refRatio = refW/refH;
// Hard coded value...
var refRatio = 240/300;
var imgH = $(this).children("img").height();
var imgW = $(this).children("img").width();
if ((imgW/imgH) < refRatio){
$(".propimage").addClass("portrait");
} else {
$(this).addClass("landscape");
}
})
</script>
Please upload You code on js fiddle or paste the link so we can see working example of your code. Meanwhile just try this code
<script>
$(".propimage").each(function(){
// Uncomment the following if you need to make this dynamic
//var refH = $(this).height();
//var refW = $(this).width();
//var refRatio = refW/refH;
// Hard coded value...
var refRatio = 240/300;
var imgH = $(this).children("img").height();
var imgW = $(this).children("img").width();
if (imgW=<200 || imgH<=300)){
$(this).children("img").css("width","100%");
$(this).css("width","100%");
} else {
$(this).children("img").css("height","100%");
$(this).css("height","100%");
}
})
</script>
I have created this fiddle where I have flicking problem in IE. Even Chrome isnt good, but in fiddle it looks more or less fine. I think problem is in "size of step" for one scroll, when you grab scroller manualy everything is smooth, but using your mousewheel leads to jumping/flicking in IE and Chrome.
window.addEventListener('scroll', function() { ...}, false);
This is my current HTML:
<div id="fakeBody">
<div id="spacer">scroll down</div>
<div class="niceBanner hide roller" id="niceBannerFrame">
<div id="bannerShadow"></div>
<div id="thumb0">
<div id="niceBannerOriginal" class="roller thumb1 thumb2"></div>
<div id="niceBannerBlur" class="roller deblur thumb1 thumb2"></div>
<div id="blackRow"></div>
</div>
</div>
</div>
Script:
window.addEventListener('scroll', function () {
var totalHeigth, currentScroll, visibleHeight;
var newResolutionBannerHeight = 0;
currentScroll = (document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;
totalHeigth = (document.height !== undefined) ? document.height : document.getElementById("fakeBody").offsetHeight;
visibleHeight = document.documentElement.clientHeight;
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight || e.clientHeight || g.clientHeight;
var curentWidth = x;
console.log('curent Width: ' + curentWidth);
if (curentWidth < 1070) {
var newBannerWidth = Math.round((curentWidth / 1070) * 1920);
var newMargin = Math.round((newBannerWidth - curentWidth) / 2);
newResolutionBannerHeight = Math.round((500 / 1920) * newBannerWidth);
} else {}
//now it is easy to recognize if visitor is at the bottom of page
if (visibleHeight + currentScroll >= totalHeigth) {
//do the magic with banner
document.getElementById("niceBannerFrame").className = "unhide";
var bannerHeight = visibleHeight + currentScroll - totalHeigth;
var style = document.createElement('style');
style.type = 'text/css';
var number = (curentWidth < 500) ? 10 + bannerHeight : 50 + bannerHeight; //not ideal solution, slower rolling for small screen, picture is realy small
if (curentWidth > 1070) {
number = (number > 500) ? 500 : number;
var opacityBlur = 1 - (number / 500);
style.innerHTML = '.roller {bottom:-' + number + 'px;} .deblur {opacity:' + opacityBlur + ';} .thumb2{height: 500px;} ';
} else {
number = (number > newResolutionBannerHeight) ? newResolutionBannerHeight : number;
var opacityBlur = 1 - (number / newResolutionBannerHeight);
style.innerHTML = '.roller {bottom:-' + number + 'px;} .deblur {opacity:' + opacityBlur + ';} .thumb2{height:' + newResolutionBannerHeight + 'px;} ';
}
document.head.appendChild(style);
} else {
//it is not good time for magic, scroll a bit more or I will hide already visible bilboard
document.getElementById("niceBannerFrame").className = "hide";
}
}, false);
and CSS:
#spacer {
height: 1000px;
background-color: whitesmoke;
}
#niceBannerOriginal {
background-image:url(http://nzworker.com/jakub-portfolio/justfiles/1920x500_original.jpg);
position: absolute;
z-index:-3;
}
#niceBannerBlur {
background-image:url(http://nzworker.com/jakub-portfolio/justfiles/1920x500_blur.jpg);
position: absolute;
z-index:-2;
}
#bannerShadow {
position:absolute;
background-image:url(http://nzworker.com/jakub-portfolio/justfiles/Stin.png);
background-repeat:repeat-x;
width:100%;
z-index:-1;
height:25px;
}
.hide {
display: none;
}
.unhide {
display: block;
}
#fakeBody {
height:1000px;
position:relative;
top:0;
left:0;
right:0;
}
#blackRow {
display:none;
}
#niceBannerFrame {
overflow: hidden;
}
#media (min-width: 1921px) {
#blackRow {
background-color: #000000;
display: block;
height:500px;
position: absolute;
width: 100%;
z-index: -6;
}
}
/*desktop resolution*/
#media (min-width: 1070px) and (max-width: 1920px) {
.thumb1 {
width: 100%;
height: 500px;
background-position: 50% 50%;
/*image centering*/
}
.thumb2 {
}
}
/*mobile and tablet resolution*/
#media (max-width: 1069px) {
.thumb2 {
width: 100%;
height: 500px;
background-repeat:no-repeat;
/*background-position: 50% 50%; image centering*/
}
#niceBannerOriginal {
background-image:url(http://nzworker.com/jakub-portfolio/justfiles/1920x500_original-thumb.jpg);
background-size: 100%;
}
#niceBannerBlur {
background-image:url(http://nzworker.com/jakub-portfolio/justfiles/1920x500_blur-thumb.jpg);
background-size: 100%;
}
}
My question is do you how to remove this flicking? Or do you know how to cut one mouse wheel step to more smaller ones?
PS: I can not use jQuery or other plugins.
I can't be 100% sure about this, but I think the flickering isn't from the amount you're scrolling, but due to the fact that you're changing the display mode, and pushing the view back up a tiny bit.
Essentially if you are just underneath the visibleHeight+currentScroll >= totalHeigth test by a couple of pixels, then currentScroll get's pushed up a tiny bit when whatever happens in there happens (I don't entirely understand what's going on, so I can't really give any better advice on that), so that it's no longer greater than totalHigth, and so it then fails the test immediately after, hence the flickering.
Worked this out by getting rid of the hide line at the end and it seems to work. Unfortunately I don't entirely understand the code, so I can't give you any better idea than that, though hopefully it points you towards a solution.
I'm using the PDF.js library to render a pdf into the canvas. That pdf has hyperlinks in there, The PDF.js library is drawing the pdf into the canvas but the hyperlinks don't work.
Any Idea if it possible that hyperlinks work into the canvas?
Thanks
Here is a fiddle that shows you how to enable annotations (including hyperlinks) in PDF files.
The original PDF file used in the fiddle is here.
I used viewer code (web/page_view.js,web/viewer.css) as refrence to write this fiddle.
HTML:
<!doctype html>
<html lang="en">
<head>
<link href="style.css" rel="stylesheet" media="screen" />
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="http://seikichi.github.io/tmp/PDFJS.0.8.715/pdf.min.js" type="text/javascript"></script>
<script src="http://seikichi.github.io/tmp/PDFJS.0.8.715/ui_utils.js"></script>
<script src="./main.js" type="text/javascript"></script>
</head>
<body>
<div id="pdfContainer" class="pdf-content">
<canvas id="the-canvas"></canvas>
<div class="annotationLayer"></div>
</div>
</body>
</html>
CSS:
body {
font-family: arial, verdana, sans-serif;
}
.pdf-content {
border: 1px solid #000000;
}
.annotationLayer > a {
display: block;
position: absolute;
}
.annotationLayer > a:hover {
opacity: 0.2;
background: #ff0;
box-shadow: 0px 2px 10px #ff0;
}
.annotText > div {
z-index: 200;
position: absolute;
padding: 0.6em;
max-width: 20em;
background-color: #FFFF99;
box-shadow: 0px 2px 10px #333;
border-radius: 7px;
}
.annotText > img {
position: absolute;
opacity: 0.6;
}
.annotText > img:hover {
opacity: 1;
}
.annotText > div > h1 {
font-size: 1.2em;
border-bottom: 1px solid #000000;
margin: 0px;
}
JavaScript:
PDFJS.workerSrc = 'http://seikichi.github.io/tmp/PDFJS.0.8.715/pdf.min.worker.js';
$(function () {
var pdfData = loadPDFData();
PDFJS.getDocument(pdfData).then(function (pdf) {
return pdf.getPage(1);
}).then(function (page) {
var scale = 1;
var viewport = page.getViewport(scale);
var $canvas = $('#the-canvas');
var canvas = $canvas.get(0);
var context = canvas.getContext("2d");
canvas.height = viewport.height;
canvas.width = viewport.width;
var $pdfContainer = $("#pdfContainer");
$pdfContainer.css("height", canvas.height + "px")
.css("width", canvas.width + "px");
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
setupAnnotations(page, viewport, canvas, $('.annotationLayer'));
});
function setupAnnotations(page, viewport, canvas, $annotationLayerDiv) {
var canvasOffset = $(canvas).offset();
var promise = page.getAnnotations().then(function (annotationsData) {
viewport = viewport.clone({
dontFlip: true
});
for (var i = 0; i < annotationsData.length; i++) {
var data = annotationsData[i];
var annotation = PDFJS.Annotation.fromData(data);
if (!annotation || !annotation.hasHtml()) {
continue;
}
var element = annotation.getHtmlElement(page.commonObjs);
data = annotation.getData();
var rect = data.rect;
var view = page.view;
rect = PDFJS.Util.normalizeRect([
rect[0],
view[3] - rect[1] + view[1],
rect[2],
view[3] - rect[3] + view[1]]);
element.style.left = (canvasOffset.left + rect[0]) + 'px';
element.style.top = (canvasOffset.top + rect[1]) + 'px';
element.style.position = 'absolute';
var transform = viewport.transform;
var transformStr = 'matrix(' + transform.join(',') + ')';
CustomStyle.setProp('transform', element, transformStr);
var transformOriginStr = -rect[0] + 'px ' + -rect[1] + 'px';
CustomStyle.setProp('transformOrigin', element, transformOriginStr);
if (data.subtype === 'Link' && !data.url) {
// In this example, I do not handle the `Link` annotations without url.
// If you want to handle those annotations, see `web/page_view.js`.
continue;
}
$annotationLayerDiv.append(element);
}
});
return promise;
}
});
function loadPDFData() {
/*jshint multistr: true */
var base64pdfData = '...'; //should contain base64 representing the PDF
function base64ToUint8Array(base64) {
var raw = atob(base64);
var uint8Array = new Uint8Array(new ArrayBuffer(raw.length));
for (var i = 0, len = raw.length; i < len; ++i) {
uint8Array[i] = raw.charCodeAt(i);
}
return uint8Array;
}
return base64ToUint8Array(base64pdfData);
}
Enable Text Selection in PDF.JS
Step 1: Adding a Element to Hold the Text Layer
<div id="text-layer"></div>
This div will be in addition to the element where the PDF is rendered, so the HTML will look like :
<canvas id="pdf-canvas"></canvas>
<div id="text-layer"></div>
Step 2 : Adding CSS for Text Layer
Add the following to your CSS file :
#text-layer {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
overflow: hidden;
opacity: 0.2;
line-height: 1.0;
}
#text-layer > div {
color: transparent;
position: absolute;
white-space: pre;
cursor: text;
transform-origin: 0% 0%;
}
Step 3: Getting the PDF Text
After the PDF has been rendered in the canvas, you need to get the text contents of the PDF, and place that text in the text layer.
// page is the page context of the PDF page
// viewport is the viewport required in renderContext
// For more see https://usefulangle.com/post/20/pdfjs-tutorial-1-preview-pdf-during-upload-wih-next-prev-buttons
page.render(renderContext).then(function() {
// Returns a promise, on resolving it will return text contents of the page
return page.getTextContent();
}).then(function(textContent) {
// PDF canvas
var pdf_canvas = $("#pdf-canvas");
// Canvas offset
var canvas_offset = pdf_canvas.offset();
// Canvas height
var canvas_height = pdf_canvas.get(0).height;
// Canvas width
var canvas_width = pdf_canvas.get(0).width;
// Assign CSS to the text-layer element
$("#text-layer").css({ left: canvas_offset.left + 'px', top: canvas_offset.top + 'px', height: canvas_height + 'px', width: canvas_width + 'px' });
// Pass the data to the method for rendering of text over the pdf canvas.
PDFJS.renderTextLayer({
textContent: textContent,
container: $("#text-layer").get(0),
viewport: viewport,
textDivs: []
});
});
source: https://usefulangle.com/post/90/javascript-pdfjs-enable-text-layer
setupAnnotations = (page, viewport, canvas, annotationLayerDiv) => {
let pdfjsLib = window['pdfjs-dist/build/pdf'];
let pdfjsViewer = window['pdfjs-dist/web/pdf_viewer'];
//BELOW--------- Create Link Service using pdf viewer
let pdfLinkService = new pdfjsViewer.PDFLinkService();
page.getAnnotations().then(function (annotationsData) {
viewport = viewport.clone({
dontFlip: true
});
let pdf_canvas = canvas;
// Render the annotation layer
annotationLayerDiv.style.left = pdf_canvas.offsetLeft + 'px';
annotationLayerDiv.style.top = pdf_canvas.offsetTop + 'px';
annotationLayerDiv.style.height = viewport.height + 'px';
annotationLayerDiv.style.width = viewport.width + 'px';
pdfjsLib.AnnotationLayer.render({
viewport: viewport,
div: annotationLayerDiv,
annotations: annotationsData,
page: page,
linkService: pdfLinkService,
enableScripting: true,
renderInteractiveForms: true
});
}
IMP ---- Do not forget to add this CSS
.annotation-layer{
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
overflow: hidden;
opacity: 1;
}
.annotation-layer section{
position: absolute;
cursor: pointer;
}
.annotation-layer section a{
display: block;
width: 100%;
height: 10px;
}
In above example, Link service instance is created using class in pdf viewer, which is being passed as parameter to annotation layer render method.
Please refer source code of PDF.js refer to /web/pdf_viewer.js - class PDFLinkService for more information.
PDF.js version - v2.9.359
I'm running an HTML5 video on my page and I'd like to make it resize edge to edge in ratio based on the browser's size. It will be set as a background with very little on the page.
To cover my ass, I'm using VideoJS to play the video and handle backwards compatibility. The fullscreen function built into the library works well, but is triggering the browser's native fullscreen function. In some browsers this means black bars, in Safari it means literally fullscreen independent of the browser window. I don't want either of these.
http://videojs.com/
Ideally, it would function like Supersized does for images. The image is always set to the full width of the page, and height is cropped towards the CENTER from there. As you resize the page smaller and smaller, it hits a min-height and begins cropping the width towards the center.
http://lara.fm/
My JavaScript knowledge is minimal, but I'm able to poke and prod to figure things out. I figured that dropping in the Supersized resizing scripts after the VideoJS library and forcing them to work on video tags would work in some way.. at least a starting place, but it didn't work.
Can someone help me understand what function can adjust width to the page, height in ratio, and crop towards the center at a certain width or height? Here's what I've got so far:
http://kzmnt.com/test/
This is a tuffie, I know. Thank you SO much.
You can try the following, (based on the demo you posted)
.video-js-box.fullScreen{
width: 100% !important;
position: relative;
background: black;
}
.fullScreen .video-js{
height: 100% !important;
margin: 0 auto;
display: block;
}
add the class .fullScreen at the video-js-box and see what happens.
I am trying to achieve the effect you described above, and I 'll let you know as soon as I find a better solution.
EDIT: Ok I think I found a solution - (VERSION 2)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>HTML5 Video Player</title>
<!-- Include the VideoJS Library -->
<script src="http://kzmnt.com/test/video.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
VideoJS.setupAllWhenReady();
</script>
<!-- Include the VideoJS Stylesheet -->
<link rel="stylesheet" href="http://videojs.com/video-js/video-js.css?v=1292015834" type="text/css" media="screen" title="Video JS">
<style>
body{margin:0;}
.video-js-box.fullScreen{
width: 100% !important;
min-width: 380px !important;
min-height: 280px !important;
position: relative;
background: #eeeeee;
position:absolute;
overflow: hidden;
top:0;
left:0;
height:100% !important;
z-index:998;
}
.fullScreen .video-js{
height:auto;
/*height: 100% !important;
width:100% !important;*/
width:100%;
top:0;
left:0;
margin: 0 auto;
display: block;
}
.video-js-box{
width:400px;
height:auto;
}
.video-js-box video{
width:400px;
height:auto;
}
#buttonImportant{
position:fixed;
top:0;
right:0;
width:100px;
height:100px;
border-radius:8px;
background:#eeeeee;
font-size:1.3em;
z-index:999;
}
</style>
</head>
<body>
<div id="buttonImportant"> CLICK ME!!! </div>
<div class="video-js-box" id="videoContainer">
<video class="video-js" preload loop fullscreen autoplay>
<source src="http://kzmnt.com/test/vid/kozmonaut_by_christina_tan.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
<source src="http://kzmnt.com/test/vid/kozmonaut_by_christina_tan.webm" type='video/webm; codecs="vp8, vorbis"' />
<source src="http://kzmnt.com/test/vid/kozmonaut_by_christina_tan.ogv" type='video/ogg; codecs="theora, vorbis"' />
<object id="flash_fallback_1" class="vjs-flash-fallback" width="1280" height="720" type="application/x-shockwave-flash"
data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf">
<param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />
<param name="allowfullscreen" value="true" />
<param name="flashvars"
value='config={"playlist":["http://kzmnt.com/test/vid/kozmonaut_by_christina_tan.png", {"url": "../vid/kozmonaut_by_christina_tan.mp4","autoPlay":true,"autoBuffering":true}]}' />
</object>
</video>
</div>
<script type="text/javascript">
var clicked = document.getElementById("buttonImportant")
var videoContainer = document.getElementById('videoContainer');
var video = videoContainer.getElementsByTagName('video')[0];
video.style.height="auto";
video.style.width="400px";
clicked.addEventListener('click',function(){
if( videoContainer.className.lastIndexOf("fullScreen")>=0 ){
videoContainer.className="video-js-box";
video.style.height = "";
video.style.width="";
}
else
{
videoContainer.className="video-js-box fullScreen";
video.style.height = "";
video.style.width="";
}
myResizerObject.prevWidth = video.offsetWidth;
myResizerObject.prevHeight = video.offsetHeight;
myResizerObject.Init();
},false);
var RESIZER = function(){
this.prevWidth = video.offsetWidth;
this.prevHeight = video.offsetHeight;
this.videoContainer = document.getElementById('videoContainer');
this.video = videoContainer.getElementsByTagName('video')[0];
this.videoStyle = this.video.style;
var ratio = this.video.offsetHeight/this.video.offsetWidth;
var that = this;
this.Init = function(){
if( that.videoContainer.className.lastIndexOf("fullScreen")>=0 )
{
var videoContOffsetWidth = that.videoContainer.offsetWidth;
var videoOffsetWidth = that.video.offsetWidth;
var videoContOffsetHeight = that.videoContainer.offsetHeight;
var videoOffsetHeight = that.video.offsetHeight;
if(that.prevWidth!= videoContOffsetWidth)
{
that.prevWidth = videoContOffsetWidth;
var desired = videoContainer.offsetHeight/videoContainer.offsetWidth;
if(desired>ratio){
that.videoStyle.width=videoContOffsetWidth*desired+videoContOffsetWidth*desired+"px";
that.videoStyle.left = -1*(videoOffsetWidth-videoContOffsetWidth)/2+'px';
}
else{
that.videoStyle.cssText="height:auto;width:100%;left:0px;top:0px;";
}
}
if(that.prevHeight!=videoContOffsetHeight)
{
that.prevHeight = videoContOffsetHeight;
var desired = videoContOffsetHeight/videoContOffsetWidth;
if(desired>ratio){ console.log(ratio);
that.videoStyle.top = '0px';
that.videoStyle.left = -1*(videoOffsetWidth-videoContOffsetWidth)/2+'px';
that.videoStyle.width = videoContOffsetHeight*desired+videoContOffsetHeight/desired+'px';
}
else
{
that.videoStyle.top = -1*(videoOffsetHeight-videoContOffsetHeight)/2+'px';
}
}
}
};
};
var myResizerObject = new RESIZER();
window.onresize = myResizerObject.Init;
</script>
</body>
</html>
Copy - paste the above code to a new file and test it : )
MAJOR EDIT 2: I refactored my code, and packaged it in a more object oriented form. Now it does move (modified top and left css attributes) so that the video remains centered when the screen ratio changes. It still does a weird little jump but it works quite well.
I will keep working on this task because I think it's a cool feature. Also I have no idea what happens or what would you like to happen during the flash fallback.
ps. I kept the click me button but it is very easy to disable it.
It looks like you're question has been answered, more or less, but for others looking for a quick and dirty way to handle this, I just pulled apart "jQuery Easy Background Resize Plug-In" and made it work for video. Pretty easy.
Html looks like this:
<div id="video-container">
<video autoplay="autoplay" id="video">
<source src="/videos/11280741.mp4" type="video/mp4" />
</video>
</div>
Javascript looks like this (look towards the bottom for the video specific stuff)
/******************************************************
* jQuery plug-in
* Easy Background Image Resizer
* Developed by J.P. Given (http://johnpatrickgiven.com)
* Useage: anyone so long as credit is left alone
******************************************************/
(function($) {
// Global Namespace
var jqez = {};
// Define the plugin
$.fn.ezBgResize = function(options) {
// Set global to obj passed
jqez = options;
// If img option is string convert to array.
// This is in preparation for accepting an slideshow of images.
if (!$.isArray(jqez.img)) {
var tmp_img = jqez.img;
jqez.img = [tmp_img]
}
$("<img/>").attr("src", jqez.img).load(function() {
jqez.width = this.width;
jqez.height = this.height;
// Create a unique div container
$("section#content").append('<div id="jq_ez_bg"></div>');
// Add the image to it.
$("#jq_ez_bg").html('<img src="' + jqez.img[0] + '" width="' + jqez.width + '" height="' + jqez.height + '" border="0">');
// First position object
$("#jq_ez_bg").css("visibility","hidden");
// Overflow set to hidden so scroll bars don't mess up image size.
$("body").css({
"overflow":"hidden"
});
resizeImage();
});
};
$(window).bind("resize", function() {
resizeImage();
});
// Actual resize function
function resizeImage() {
$("#jq_ez_bg").css({
"position":"fixed",
"top":"0px",
"left":"0px",
"z-index":"-1",
"overflow":"hidden",
"width":$(window).width() + "px",
"height":$(window).height() + "px",
"opacity" : jqez.opacity
});
// Image relative to its container
$("#jq_ez_bg").children('img').css("position", "relative");
// Resize the img object to the proper ratio of the window.
var iw = $("#jq_ez_bg").children('img').width();
var ih = $("#jq_ez_bg").children('img').height();
if ($(window).width() > $(window).height()) {
//console.log(iw, ih);
if (iw > ih) {
var fRatio = iw/ih;
$("#jq_ez_bg").children('img').css("width",$(window).width() + "px");
$("#jq_ez_bg").children('img').css("height",Math.round($(window).width() * (1/fRatio)));
var newIh = Math.round($(window).width() * (1/fRatio));
if(newIh < $(window).height()) {
var fRatio = ih/iw;
$("#jq_ez_bg").children('img').css("height",$(window).height());
$("#jq_ez_bg").children('img').css("width",Math.round($(window).height() * (1/fRatio)));
}
} else {
var fRatio = ih/iw;
$("#jq_ez_bg").children('img').css("height",$(window).height());
$("#jq_ez_bg").children('img').css("width",Math.round($(window).height() * (1/fRatio)));
}
} else {
var fRatio = ih/iw;
$("#jq_ez_bg").children('img').css("height",$(window).height());
$("#jq_ez_bg").children('img').css("width",Math.round($(window).height() * (1/fRatio)));
}
// Center the image
if (typeof(jqez.center) == 'undefined' || jqez.center) {
if ($("#jq_ez_bg").children('img').width() > $(window).width()) {
var this_left = ($("#jq_ez_bg").children('img').width() - $(window).width()) / 2;
$("#jq_ez_bg").children('img').css({
"top" : 0,
"left" : -this_left
});
}
if ($("#jq_ez_bg").children('img').height() > $(window).height()) {
var this_height = ($("#jq_ez_bg").children('img').height() - $(window).height()) / 2;
$("#jq_ez_bg").children('img').css({
"left" : 0,
"top" : -this_height
});
}
}
$("#jq_ez_bg").css({
"visibility" : "visible"
});
// Allow scrolling again
$("body").css({
"overflow":"auto"
});
$("#video-container").css({
"position":"fixed",
"top":"0px",
"left":"0px",
"z-index":"-1",
"overflow":"hidden",
"width":$(window).width() + "px",
"height":$(window).height() + "px",
"opacity" : jqez.opacity
});
$("#video-container").children('video').css("position", "relative");
var iw = $("#video-container").children('video').width();
var ih = $("#video-container").children('video').height();
if ($(window).width() > $(window).height()) {
//console.log(iw, ih);
if (iw > ih) {
var fRatio = iw/ih;
$("#video-container").children('video').css("width",$(window).width() + "px");
$("#video-container").children('video').css("height",Math.round($(window).width() * (1/fRatio)));
var newIh = Math.round($(window).width() * (1/fRatio));
if(newIh < $(window).height()) {
var fRatio = ih/iw;
$("#video-container").children('video').css("height",$(window).height());
$("#video-container").children('video').css("width",Math.round($(window).height() * (1/fRatio)));
}
} else {
var fRatio = ih/iw;
$("#video-container").children('video').css("height",$(window).height());
$("#video-container").children('video').css("width",Math.round($(window).height() * (1/fRatio)));
}
} else {
var fRatio = ih/iw;
$("#video-container").children('video').css("height",$(window).height());
$("#video-container").children('video').css("width",Math.round($(window).height() * (1/fRatio)));
}
// Center the image
if (typeof(jqez.center) == 'undefined' || jqez.center) {
if ($("#video-container").children('video').width() > $(window).width()) {
var this_left = ($("#video-container").children('video').width() - $(window).width()) / 2;
$("#video-container").children('video').css({
"top" : 0,
"left" : -this_left
});
}
if ($("#video-container").children('video').height() > $(window).height()) {
var this_height = ($("#video-container").children('video').height() - $(window).height()) / 2;
$("#video-container").children('video').css({
"left" : 0,
"top" : -this_height
});
}
}
$("#video-container").css({
"visibility" : "visible"
});
}
})(jQuery);