Image with declared width and height renders square before load - html

I have images with declared widths and heights, e.g.:
<img src="foo.jpg" width="1500" height="1800" alt="bar" />
They are within a responsive grid, so they display at max-width: 100%. They are lazyloaded in. The problem is that despite having height: auto;, the images always display square before they are loaded, which creates a jump in page height when they have finished loading.
So the above image example, in my 960px width grid, would display a placeholder at 960px x 960px until the full image loads, at which point it will be 960px x Y (where Y is the correct height).
My question is how can I get the placeholder image to mimic the final loaded dimensions of the actual image?

You can achieve the desired effect with the following solution.
HTML:
<img src="blank.gif" class="lazy" data-src="foo.png" width="1500" height="1800" alt="bar">
▲ ▲
║ ╚═══ The class will be used for the lazy loader below
║
╚═══ Use faulty gif here to hide it from showing before loaded
Hint: If you want the placeholder rectangle to be visible and in one color, consider using a 1x1 px image for blank.gif. It will load
very fast and will stretch nicely to your proportions, filling it with
the color of your choosing.
JavaScript:
/* lazyload.js (c) Lorenzo Giuliani
* MIT License (http://www.opensource.org/licenses/mit-license.html)
*
* expects a list of:
* `<img src="blank.gif" data-src="my_image.png" width="600" height="400" class="lazy">`
*/
!function(window){
var $q = function(q, res){
if (document.querySelectorAll) {
res = document.querySelectorAll(q);
} else {
var d=document
, a=d.styleSheets[0] || d.createStyleSheet();
a.addRule(q,'f:b');
for(var l=d.all,b=0,c=[],f=l.length;b<f;b++)
l[b].currentStyle.f && c.push(l[b]);
a.removeRule(0);
res = c;
}
return res;
}
, addEventListener = function(evt, fn){
window.addEventListener
? this.addEventListener(evt, fn, false)
: (window.attachEvent)
? this.attachEvent('on' + evt, fn)
: this['on' + evt] = fn;
}
, _has = function(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
;
function loadImage (el, fn) {
var img = new Image()
, src = el.getAttribute('data-src');
img.onload = function() {
if (!! el.parent)
el.parent.replaceChild(img, el)
else
el.src = src;
fn? fn() : null;
}
img.src = src;
}
function elementInViewport(el) {
var rect = el.getBoundingClientRect()
return (
rect.top >= 0
&& rect.left >= 0
&& rect.top <= (window.innerHeight || document.documentElement.clientHeight)
)
}
var images = new Array()
, query = $q('img.lazy')
, processScroll = function(){
for (var i = 0; i < images.length; i++) {
if (elementInViewport(images[i])) {
loadImage(images[i], function () {
images.splice(i, i);
});
}
};
}
;
// Array.prototype.slice.call is not callable under our lovely IE8
for (var i = 0; i < query.length; i++) {
images.push(query[i]);
};
processScroll();
addEventListener('scroll',processScroll);
}(this);
Sources:
The Lazyload script can be found here.

The following is the only solution that worked 100% of the time, and is much simpler:
https://css-tricks.com/preventing-content-reflow-from-lazy-loaded-images/
In short you can use an SVG placeholder image that contains the dimenions:
<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 3 2'%3E%3C/svg%3E" data-src="//picsum.photos/900/600" alt="Lazy loading test image" />
Here is an React example:
const placeholderSrc = (width, height) => `data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}"%3E%3C/svg%3E`
const lazyImage = ({url, width, height, alt}) => {
return (
<img
src={placeholderSrc(width, height)}
data-src={url}
alt={alt} />
)
}

Here i made a FIDDLE for you
The Main thing is to generate a div around it and setting the height and the width according to what it should be after it loads. then you can load it inside that container and even with a smooth effect ;)
HTML
<div class="site-wrapper">
<div class="lazyload" data-src="http://tinyurl.com/py2nunk" data-width="1920" data-height="1200"></div>
</div>
CSS
.site-wrapper {
width:960px;
}
.lazyload {
max-width: 100%;
border: 1px solid #000;
}
.lazyload img {
max-width: 100%;
}
JAVASCRIPT
$(document).ready(function() {
$('.lazyload').each(function() {
var parentwidth = $(this).parent().width();
var width = $(this).attr('data-width');
var height = $(this).attr('data-height');
if(parentwidth < width) {
height = (parentwidth/width*height);
width = parentwidth;
}
$(this).css({ width: width+'px', height: height+'px'});
});
// simulating lazyload
setTimeout(function() {
$('.lazyload').each(function() {
img = $('<img>', { 'class': 'lazyloaded' }).css({display: 'none'});
original = $(this);
$(img).load( function(){
original.append(img);
$(this).fadeIn(200);
}).attr('src', $(this).attr('data-src'));
});
}, 5000);
});
Let me know if this is what you need or not so i can change according to what you need.

Right off the bat I notice that you are using px instead of % for width and height. Responsive HTML 5 DOCType. you should use percentage. There to many phones and tablets out there visiting your website.
Use meta tag viewport in your headers. Try something like this
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
For further information on how to correctly re-size your web page for any device go here https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag
I recon-mind that you use CSS to control the height and width of the image try to stay away from attributes if possible. Use min and max along with your width and height sectors for width and height in you CSS code. You don't need JavaScript to solve your issues

Could you please add required max-height for the image in css. I think this would solve your problem.

At time of writing none of the answers explain why this happens or how to overcome it. I found another question which is the same as this one that explains an interesting "hack" to get around this.

Related

Dynamically change font-size within parent element with no overflow [duplicate]

I need to display user entered text into a fixed size div. What i want is for the font size to be automatically adjusted so that the text fills the box as much as possible.
So - If the div is 400px x 300px. If someone enters ABC then it's really big font. If they enter a paragraph, then it would be a tiny font.
I'd probably want to start with a maximum font size - maybe 32px, and while the text is too big to fit the container, shrink the font size until it fits.
This is what I ended up with:
Here is a link to the plugin: https://plugins.jquery.com/textfill/
And a link to the source: http://jquery-textfill.github.io/
;(function($) {
$.fn.textfill = function(options) {
var fontSize = options.maxFontPixels;
var ourText = $('span:visible:first', this);
var maxHeight = $(this).height();
var maxWidth = $(this).width();
var textHeight;
var textWidth;
do {
ourText.css('font-size', fontSize);
textHeight = ourText.height();
textWidth = ourText.width();
fontSize = fontSize - 1;
} while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
return this;
}
})(jQuery);
$(document).ready(function() {
$('.jtextfill').textfill({ maxFontPixels: 36 });
});
and my HTML is like this
<div class='jtextfill' style='width:100px;height:50px;'>
<span>My Text Here</span>
</div>
I didn't find any of the previous solutions to be adequate enough due to bad performance, so I made my own that uses simple math instead of looping. Should work fine in all browsers as well.
According to this performance test case it is much faster then the other solutions found here.
(function($) {
$.fn.textfill = function(maxFontSize) {
maxFontSize = parseInt(maxFontSize, 10);
return this.each(function(){
var ourText = $("span", this),
parent = ourText.parent(),
maxHeight = parent.height(),
maxWidth = parent.width(),
fontSize = parseInt(ourText.css("fontSize"), 10),
multiplier = maxWidth/ourText.width(),
newSize = (fontSize*(multiplier-0.1));
ourText.css(
"fontSize",
(maxFontSize > 0 && newSize > maxFontSize) ?
maxFontSize :
newSize
);
});
};
})(jQuery);
If you want to contribute I've added this to Gist.
As much as I love the occasional upvotes I get for this answer (thanks!), this is really not the greatest approach to this problem. Please check out some of the other wonderful answers here, especially the ones that have found solutions without looping.
Still, for the sake of reference, here's my original answer:
<html>
<head>
<style type="text/css">
#dynamicDiv
{
background: #CCCCCC;
width: 300px;
height: 100px;
font-size: 64px;
overflow: hidden;
}
</style>
<script type="text/javascript">
function shrink()
{
var textSpan = document.getElementById("dynamicSpan");
var textDiv = document.getElementById("dynamicDiv");
textSpan.style.fontSize = 64;
while(textSpan.offsetHeight > textDiv.offsetHeight)
{
textSpan.style.fontSize = parseInt(textSpan.style.fontSize) - 1;
}
}
</script>
</head>
<body onload="shrink()">
<div id="dynamicDiv"><span id="dynamicSpan">DYNAMIC FONT</span></div>
</body>
</html>
And here's a version with classes:
<html>
<head>
<style type="text/css">
.dynamicDiv
{
background: #CCCCCC;
width: 300px;
height: 100px;
font-size: 64px;
overflow: hidden;
}
</style>
<script type="text/javascript">
function shrink()
{
var textDivs = document.getElementsByClassName("dynamicDiv");
var textDivsLength = textDivs.length;
// Loop through all of the dynamic divs on the page
for(var i=0; i<textDivsLength; i++) {
var textDiv = textDivs[i];
// Loop through all of the dynamic spans within the div
var textSpan = textDiv.getElementsByClassName("dynamicSpan")[0];
// Use the same looping logic as before
textSpan.style.fontSize = 64;
while(textSpan.offsetHeight > textDiv.offsetHeight)
{
textSpan.style.fontSize = parseInt(textSpan.style.fontSize) - 1;
}
}
}
</script>
</head>
<body onload="shrink()">
<div class="dynamicDiv"><span class="dynamicSpan">DYNAMIC FONT</span></div>
<div class="dynamicDiv"><span class="dynamicSpan">ANOTHER DYNAMIC FONT</span></div>
<div class="dynamicDiv"><span class="dynamicSpan">AND YET ANOTHER DYNAMIC FONT</span></div>
</body>
</html>
Most of the other answers use a loop to reduce the font-size until it fits on the div, this is VERY slow since the page needs to re-render the element each time the font changes size. I eventually had to write my own algorithm to make it perform in a way that allowed me to update its contents periodically without freezing the user browser. I added some other functionality (rotating text, adding padding) and packaged it as a jQuery plugin, you can get it at:
https://github.com/DanielHoffmann/jquery-bigtext
simply call
$("#text").bigText();
and it will fit nicely on your container.
See it in action here:
http://danielhoffmann.github.io/jquery-bigtext/
For now it has some limitations, the div must have a fixed height and width and it does not support wrapping text into multiple lines.
I will work on getting an option to set the maximum font-size.
Edit: I have found some more problems with the plugin, it does not handle other box-model besides the standard one and the div can't have margins or borders. I will work on it.
Edit2: I have now fixed those problems and limitations and added more options. You can set maximum font-size and you can also choose to limit the font-size using either width, height or both. I will work into accepting a max-width and max-height values in the wrapper element.
Edit3: I have updated the plugin to version 1.2.0. Major cleanup on the code and new options (verticalAlign, horizontalAlign, textAlign) and support for inner elements inside the span tag (like line-breaks or font-awesome icons.)
This is based on what GeekyMonkey posted above, with some modifications.
; (function($) {
/**
* Resize inner element to fit the outer element
* #author Some modifications by Sandstrom
* #author Code based on earlier works by Russ Painter (WebDesign#GeekyMonkey.com)
* #version 0.2
*/
$.fn.textfill = function(options) {
options = jQuery.extend({
maxFontSize: null,
minFontSize: 8,
step: 1
}, options);
return this.each(function() {
var innerElements = $(this).children(':visible'),
fontSize = options.maxFontSize || innerElements.css("font-size"), // use current font-size by default
maxHeight = $(this).height(),
maxWidth = $(this).width(),
innerHeight,
innerWidth;
do {
innerElements.css('font-size', fontSize);
// use the combined height of all children, eg. multiple <p> elements.
innerHeight = $.map(innerElements, function(e) {
return $(e).outerHeight();
}).reduce(function(p, c) {
return p + c;
}, 0);
innerWidth = innerElements.outerWidth(); // assumes that all inner elements have the same width
fontSize = fontSize - options.step;
} while ((innerHeight > maxHeight || innerWidth > maxWidth) && fontSize > options.minFontSize);
});
};
})(jQuery);
Here's an improved looping method that uses binary search to find the largest possible size that fits into the parent in the fewest steps possible (this is faster and more accurate than stepping by a fixed font size). The code is also optimized in several ways for performance.
By default, 10 binary search steps will be performed, which will get within 0.1% of the optimal size. You could instead set numIter to some value N to get within 1/2^N of the optimal size.
Call it with a CSS selector, e.g.: fitToParent('.title-span');
/**
* Fit all elements matching a given CSS selector to their parent elements'
* width and height, by adjusting the font-size attribute to be as large as
* possible. Uses binary search.
*/
var fitToParent = function(selector) {
var numIter = 10; // Number of binary search iterations
var regexp = /\d+(\.\d+)?/;
var fontSize = function(elem) {
var match = elem.css('font-size').match(regexp);
var size = match == null ? 16 : parseFloat(match[0]);
return isNaN(size) ? 16 : size;
}
$(selector).each(function() {
var elem = $(this);
var parentWidth = elem.parent().width();
var parentHeight = elem.parent().height();
if (elem.width() > parentWidth || elem.height() > parentHeight) {
var maxSize = fontSize(elem), minSize = 0.1;
for (var i = 0; i < numIter; i++) {
var currSize = (minSize + maxSize) / 2;
elem.css('font-size', currSize);
if (elem.width() > parentWidth || elem.height() > parentHeight) {
maxSize = currSize;
} else {
minSize = currSize;
}
}
elem.css('font-size', minSize);
}
});
};
I've created a directive for AngularJS - heavely inspired by GeekyMonkey's answer but without the jQuery dependency.
Demo: http://plnkr.co/edit/8tPCZIjvO3VSApSeTtYr?p=preview
Markup
<div class="fittext" max-font-size="50" text="Your text goes here..."></div>
Directive
app.directive('fittext', function() {
return {
scope: {
minFontSize: '#',
maxFontSize: '#',
text: '='
},
restrict: 'C',
transclude: true,
template: '<div ng-transclude class="textContainer" ng-bind="text"></div>',
controller: function($scope, $element, $attrs) {
var fontSize = $scope.maxFontSize || 50;
var minFontSize = $scope.minFontSize || 8;
// text container
var textContainer = $element[0].querySelector('.textContainer');
angular.element(textContainer).css('word-wrap', 'break-word');
// max dimensions for text container
var maxHeight = $element[0].offsetHeight;
var maxWidth = $element[0].offsetWidth;
var textContainerHeight;
var textContainerWidth;
var resizeText = function(){
do {
// set new font size and determine resulting dimensions
textContainer.style.fontSize = fontSize + 'px';
textContainerHeight = textContainer.offsetHeight;
textContainerWidth = textContainer.offsetWidth;
// shrink font size
var ratioHeight = Math.floor(textContainerHeight / maxHeight);
var ratioWidth = Math.floor(textContainerWidth / maxWidth);
var shrinkFactor = ratioHeight > ratioWidth ? ratioHeight : ratioWidth;
fontSize -= shrinkFactor;
} while ((textContainerHeight > maxHeight || textContainerWidth > maxWidth) && fontSize > minFontSize);
};
// watch for changes to text
$scope.$watch('text', function(newText, oldText){
if(newText === undefined) return;
// text was deleted
if(oldText !== undefined && newText.length < oldText.length){
fontSize = $scope.maxFontSize;
}
resizeText();
});
}
};
});
I forked the script above from Marcus Ekwall: https://gist.github.com/3945316 and tweaked it to my preferences, it now fires when the window is resized, so that the child always fits its container. I've pasted the script below for reference.
(function($) {
$.fn.textfill = function(maxFontSize) {
maxFontSize = parseInt(maxFontSize, 10);
return this.each(function(){
var ourText = $("span", this);
function resizefont(){
var parent = ourText.parent(),
maxHeight = parent.height(),
maxWidth = parent.width(),
fontSize = parseInt(ourText.css("fontSize"), 10),
multiplier = maxWidth/ourText.width(),
newSize = (fontSize*(multiplier));
ourText.css("fontSize", maxFontSize > 0 && newSize > maxFontSize ? maxFontSize : newSize );
}
$(window).resize(function(){
resizefont();
});
resizefont();
});
};
})(jQuery);
Here's my modification of the OP's answer.
In short, many people who tried to optimize this complained that a loop was being used. Yes, while loops can be slow, other approaches can be inaccurate.
Therefore, my approach uses Binary Search to find the best Font Size:
$.fn.textfill = function()
{
var self = $(this);
var parent = self.parent();
var attr = self.attr('max-font-size');
var maxFontSize = parseInt(attr, 10);
var unit = attr.replace(maxFontSize, "");
var minFontSize = parseInt(self.attr('min-font-size').replace(unit, ""));
var fontSize = (maxFontSize + minFontSize) / 2;
var maxHeight = parent.height();
var maxWidth = parent.width();
var textHeight;
var textWidth;
do
{
self.css('font-size', fontSize + unit);
textHeight = self.height();
textWidth = self.width();
if(textHeight > maxHeight || textWidth > maxWidth)
{
maxFontSize = fontSize;
fontSize = Math.floor((fontSize + minFontSize) / 2);
}
else if(textHeight < maxHeight || textWidth < maxWidth)
{
minFontSize = fontSize;
fontSize = Math.floor((fontSize + maxFontSize) / 2);
}
else
break;
}
while(maxFontSize - minFontSize > 1 && maxFontSize > minFontSize);
self.css('font-size', fontSize + unit);
return this;
}
function resizeText()
{
$(".textfill").textfill();
}
$(document).ready(resizeText);
$(window).resize(resizeText);
This also allows the element to specify the minimum and maximum font:
<div class="container">
<div class="textfill" min-font-size="10px" max-font-size="72px">
Text that will fill the container, to the best of its abilities, and it will <i>never</i> have overflow.
</div>
</div>
Furthermore, this algorithm is unitless. You may specify em, rem, %, etc. and it will use that for its final result.
Here's the Fiddle: https://jsfiddle.net/fkhqhnqe/1/
I had exactly the same problem with my website. I have a page that is displayed on a projector, on walls, big screens..
As I don't know the max size of my font, I re-used the plugin above of #GeekMonkey but incrementing the fontsize :
$.fn.textfill = function(options) {
var defaults = { innerTag: 'span', padding: '10' };
var Opts = jQuery.extend(defaults, options);
return this.each(function() {
var ourText = $(Opts.innerTag + ':visible:first', this);
var fontSize = parseFloat(ourText.css('font-size'),10);
var doNotTrepass = $(this).height()-2*Opts.padding ;
var textHeight;
do {
ourText.css('font-size', fontSize);
textHeight = ourText.height();
fontSize = fontSize + 2;
} while (textHeight < doNotTrepass );
});
};
The proposed iterative solutions can be sped up dramatically on two fronts:
1) Multiply the font size by some constant, rather than adding or subtracting 1.
2) First, zero in using a course constant, say, double the size each loop. Then, with a rough idea of where to start, do the same thing with a finer adjustment, say, multiply by 1.1. While the perfectionist might want the exact integer pixel size of the ideal font, most observers don't notice the difference between 100 and 110 pixels. If you are a perfectionist, then repeat a third time with an even finer adjustment.
Rather than writing a specific routine or plug-in that answers the exact question, I just rely on the basic ideas and write variations of the code to handle all kinds of layout issues, not just text, including fitting divs, spans, images,... by width, height, area,... within a container, matching another element....
Here's an example:
var nWindowH_px = jQuery(window).height();
var nWas = 0;
var nTry = 5;
do{
nWas = nTry;
nTry *= 2;
jQuery('#divTitle').css('font-size' ,nTry +'px');
}while( jQuery('#divTitle').height() < nWindowH_px );
nTry = nWas;
do{
nWas = nTry;
nTry = Math.floor( nTry * 1.1 );
jQuery('#divTitle').css('font-size' ,nTry +'px');
}while( nWas != nTry && jQuery('#divTitle').height() < nWindowH_px );
jQuery('#divTitle').css('font-size' ,nWas +'px');
Here is a version of the accepted answer which can also take a minFontSize parameter.
(function($) {
/**
* Resizes an inner element's font so that the inner element completely fills the outer element.
* #author Russ Painter WebDesign#GeekyMonkey.com
* #author Blake Robertson
* #version 0.2 -- Modified it so a min font parameter can be specified.
*
* #param {Object} Options which are maxFontPixels (default=40), innerTag (default='span')
* #return All outer elements processed
* #example <div class='mybigdiv filltext'><span>My Text To Resize</span></div>
*/
$.fn.textfill = function(options) {
var defaults = {
maxFontPixels: 40,
minFontPixels: 10,
innerTag: 'span'
};
var Opts = jQuery.extend(defaults, options);
return this.each(function() {
var fontSize = Opts.maxFontPixels;
var ourText = $(Opts.innerTag + ':visible:first', this);
var maxHeight = $(this).height();
var maxWidth = $(this).width();
var textHeight;
var textWidth;
do {
ourText.css('font-size', fontSize);
textHeight = ourText.height();
textWidth = ourText.width();
fontSize = fontSize - 1;
} while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > Opts.minFontPixels);
});
};
})(jQuery);
You can use FitText.js (github page) to solve this problem. Is really small and efficient compared to TextFill. TextFill uses an expensive while loop and FitText don't.
Also FitText is more flexible (I use it in a proyect with very special requirements and works like a champ!).
HTML:
<div class="container">
<h1 id="responsive_headline">Your fancy title</h1>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="jquery.fittext.js"></script>
<script>
jQuery("#responsive_headline").fitText();
</script>
You also can set options to it:
<script>
jQuery("#responsive_headline").fitText(1, { minFontSize: '30px', maxFontSize: '90px'});
</script>
CSS:
#responsive_headline {
width: 100%;
display: block;
}
And if you need it, FitText also has a no-jQuery version.
EDIT: This code was used to show notes on top of a HTML5 video. It changes the font-size on the fly when the video is resized (when the browser window is resized.) The notes was connected to the video (just like notes on YouTube), which is why the code uses instances instead of a DOM handle directly.
As per request I'll throw in some code that I used to achieve this. (Text boxes over an HTML5 video.) The code was written a long time ago, and I quite frankly think it's pretty messy. Since the question is already answered and an answer is already accepted a long time ago I don't bother rewriting this. But if anyone wants to simplify this a bit, you're more than welcome!
// Figure out the text size:
var text = val['text'];
var letters = text.length;
var findMultiplier = function(x) { // g(x)
/* By analysing some functions with regression, the resulting function that
gives the best font size with respect to the number of letters and the size
of the note is:
g(x) = 8.3 - 2.75x^0.15 [1 < x < 255]
f(x) = g(letters) * (x / 1000)^0.5
Font size = f(size)
*/
return 8.3 - 2.75 * Math.pow(x, 0.15);
};
var findFontSize = function(x) { // f(x)
return findMultiplier(letters) * Math.pow(x / 1000, 0.5);
};
val.setFontSizeListener = function() {
p.style.fontSize = '1px'; // So the text should not overflow the box when measuring.
var noteStyle = window.getComputedStyle(table);
var width = noteStyle.getPropertyValue('width');
var height = noteStyle.getPropertyValue('height');
var size = width.substring(0, width.length - 2) * height.substring(0, height.length - 2);
p.style.fontSize = findFontSize(size) + 'px';
};
window.addEventListener('resize', val.setFontSizeListener);
You'll probably need to tweak these numbers from font-family to font-family. A good way to do this is download a free graph visualizer called GeoGebra. Change the length of the text and the size of the box. Then you manually set the size. Plot the manual results into the coordinate system. Then you enter the two equations I've posted here and you tweak the numbers until "my" graph fits your own manually plotted points.
Just wanted to add my version for contenteditables.
$.fn.fitInText = function() {
this.each(function() {
let textbox = $(this);
let textboxNode = this;
let mutationCallback = function(mutationsList, observer) {
if (observer) {
observer.disconnect();
}
textbox.css('font-size', 0);
let desiredHeight = textbox.css('height');
for (i = 12; i < 50; i++) {
textbox.css('font-size', i);
if (textbox.css('height') > desiredHeight) {
textbox.css('font-size', i - 1);
break;
}
}
var config = {
attributes: true,
childList: true,
subtree: true,
characterData: true
};
let newobserver = new MutationObserver(mutationCallback);
newobserver.observe(textboxNode, config);
};
mutationCallback();
});
}
$('#inner').fitInText();
#outer {
display: table;
width: 100%;
}
#inner {
border: 1px solid black;
height: 170px;
text-align: center;
display: table-cell;
vertical-align: middle;
word-break: break-all;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="outer">
<div id="inner" contenteditable=true>
TEST
</div>
</div>
This uses binary search, doing 10 iterations. The naive way was to do a while loop and increase the font size by 1 until the element started to overflow. You can determine when an element begins to overflow using element.offsetHeight and element.scrollHeight. If scrollHeight is bigger than offsetHeight, you have a font size that is too big.
Binary search is a much better algorithm for this. It also is limited by the number of iterations you want to perform. Simply call flexFont and insert the div id and it will adjust the font size between 8px and 96px.
I have spent some time researching this topic and trying different libraries, but ultimately I think this is the easiest and most straightforward solution that will actually work.
Note if you want you can change to use offsetWidth and scrollWidth, or add both to this function.
// Set the font size using overflow property and div height
function flexFont(divId) {
var content = document.getElementById(divId);
content.style.fontSize = determineMaxFontSize(content, 8, 96, 10, 0) + "px";
};
// Use binary search to determine font size
function determineMaxFontSize(content, min, max, iterations, lastSizeNotTooBig) {
if (iterations === 0) {
return lastSizeNotTooBig;
}
var obj = fontSizeTooBig(content, min, lastSizeNotTooBig);
// if `min` too big {....min.....max.....}
// search between (avg(min, lastSizeTooSmall)), min)
// if `min` too small, search between (avg(min,max), max)
// keep track of iterations, and the last font size that was not too big
if (obj.tooBig) {
(lastSizeTooSmall === -1) ?
determineMaxFontSize(content, min / 2, min, iterations - 1, obj.lastSizeNotTooBig, lastSizeTooSmall) :
determineMaxFontSize(content, (min + lastSizeTooSmall) / 2, min, iterations - 1, obj.lastSizeNotTooBig, lastSizeTooSmall);
} else {
determineMaxFontSize(content, (min + max) / 2, max, iterations - 1, obj.lastSizeNotTooBig, min);
}
}
// determine if fontSize is too big based on scrollHeight and offsetHeight,
// keep track of last value that did not overflow
function fontSizeTooBig(content, fontSize, lastSizeNotTooBig) {
content.style.fontSize = fontSize + "px";
var tooBig = content.scrollHeight > content.offsetHeight;
return {
tooBig: tooBig,
lastSizeNotTooBig: tooBig ? lastSizeNotTooBig : fontSize
};
}
I got the same problem and the solution is basically use javascript to control font-size.
Check this example on codepen:
https://codepen.io/ThePostModernPlatonic/pen/BZKzVR
This is example is only for height, maybe you need to put some if's about the width.
try to resize it
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sem título</title>
<style>
</style>
</head>
<body>
<div style="height:100vh;background-color: tomato;" id="wrap">
<h1 class="quote" id="quotee" style="padding-top: 56px">Because too much "light" doesn't <em>illuminate</em> our paths and warm us, it only blinds and burns us.</h1>
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
var multiplexador = 3;
initial_div_height = document.getElementById ("wrap").scrollHeight;
setInterval(function(){
var div = document.getElementById ("wrap");
var frase = document.getElementById ("quotee");
var message = "WIDTH div " + div.scrollWidth + "px. "+ frase.scrollWidth+"px. frase \n";
message += "HEIGHT div " + initial_div_height + "px. "+ frase.scrollHeight+"px. frase \n";
if (frase.scrollHeight < initial_div_height - 30){
multiplexador += 1;
$("#quotee").css("font-size", multiplexador);
}
console.log(message);
}, 10);
</script>
</html>
I did like
let name = "Making statements based on opinion; back them up with references or personal experience."
let originFontSize = 15;
let maxDisplayCharInLine = 50;
let fontSize = Math.min(originFontSize, originFontSize / (name.length / maxDisplayCharInLine));
I have found a way to prevent the use of loops to shrink the text. It adjusts the font-size by multiplying it for the rate between container's width and content width. So if the container's width is 1/3 of the content, the font-size will be reduced by 1/3 and will container's width. To scale up, I have used a while loop, until content is bigger than container.
function fitText(outputSelector){
// max font size in pixels
const maxFontSize = 50;
// get the DOM output element by its selector
let outputDiv = document.getElementById(outputSelector);
// get element's width
let width = outputDiv.clientWidth;
// get content's width
let contentWidth = outputDiv.scrollWidth;
// get fontSize
let fontSize = parseInt(window.getComputedStyle(outputDiv, null).getPropertyValue('font-size'),10);
// if content's width is bigger than elements width - overflow
if (contentWidth > width){
fontSize = Math.ceil(fontSize * width/contentWidth,10);
fontSize = fontSize > maxFontSize ? fontSize = maxFontSize : fontSize - 1;
outputDiv.style.fontSize = fontSize+'px';
}else{
// content is smaller than width... let's resize in 1 px until it fits
while (contentWidth === width && fontSize < maxFontSize){
fontSize = Math.ceil(fontSize) + 1;
fontSize = fontSize > maxFontSize ? fontSize = maxFontSize : fontSize;
outputDiv.style.fontSize = fontSize+'px';
// update widths
width = outputDiv.clientWidth;
contentWidth = outputDiv.scrollWidth;
if (contentWidth > width){
outputDiv.style.fontSize = fontSize-1+'px';
}
}
}
}
This code is part of a test that I have uploaded to Github https://github.com/ricardobrg/fitText/
I went with geekMonkey solution, but it's too slow. What he does, is he adjusts the font size to maximum (maxFontPixels) and then checks if it fits inside the container. else it reduces the font size by 1px and checks again. Why not simply check the previous container for the height and submit that value? (yes, I know why, but I now made a solution, that only works on the height and also has a min/max option)
Here is a much quicker solution:
var index_letters_resize;
(index_letters_resize = function() {
$(".textfill").each(function() {
var
$this = $(this),
height = Math.min( Math.max( parseInt( $this.height() ), 40 ), 150 );
$this.find(".size-adjust").css({
fontSize: height
});
});
}).call();
$(window).on('resize', function() {
index_letters_resize();
);
and this would be the HTML:
<div class="textfill">
<span class="size-adjust">adjusted element</span>
other variable stuff that defines the container size
</div>
Again: this solution ONLY checks for the height of the container. That's why this function does not has to check, if the element fits inside. But I also implemented a min/max value (40min, 150max) so for me this works perfectly fine (and also works on window resize).
Here is another version of this solution:
shrinkTextInElement : function(el, minFontSizePx) {
if(!minFontSizePx) {
minFontSizePx = 5;
}
while(el.offsetWidth > el.parentNode.offsetWidth || el.offsetHeight > el.parentNode.offsetHeight) {
var newFontSize = (parseInt(el.style.fontSize, 10) - 3);
if(newFontSize <= minFontSizePx) {
break;
}
el.style.fontSize = newFontSize + "px";
}
}

Change background colour (scrolling) when an element comes to a certain point (Responsive)

Sorry guys, I am very new to Javascript. I have searched for similar solutions before posting here.
I want to change the background colour, every time that multiple div tags, with specific ids, come 150 pixels before they reach the browser top. I want it to work in different devices correctly. I tried different things in javascript but none gave me the responsiveness I want. When I reduce the browser's width, the text is folding and the div/ids positions change. So, my logic is... if, for example, a div with id="One" is 150px from top, change the background colour.
var one = document.getElementById("one");
var two = document.getElementById("two");
var three = document.getElementById("three");
window.addEventListener('scroll', () => {
if(one.getBoundingClientRect().top < 150){
document.body.addClass = "bg-one";
}
});
.site-main{
background-color: white;
}
.bg-one{
background-color: red;
}
.bg-two{
background-color: blue;
}
.bg-three{
background-color: yellow;
}
<body class="site-main" id="main">
<div id="one" class="">Text</div>
<div id="two" class="">Text</div>
<div id="three" class="">Text</div
</body>
I was thinking about that, but it doesn't work.
My solution would be to add an event listener on window scroll
window.onscroll = function(){ft_onscroll()};
in this function, you get the current scroll position. Compare it to your element position to do what you want.
one_y = one.getBoundingClientRect().top;
function ft_onscroll(){
y = window.scrollY;
if(one_y > y){
//change background color
}
}
I made it. My final code is this. Maybe I will make it shorter.
window.onscroll = function(){
fromTop_onscroll();
};
function fromTop_onscroll(){
var main = document.getElementById("main");
var one = document.getElementById("one");
one_distance = one.getBoundingClientRect().top; // distance from top
var two = document.getElementById("two");
two_distance = two.getBoundingClientRect().top; // distance from top
if(one_distance < 150 && two_distance > 150){
main.classList.add("bg-one");
main.classList.remove("site-main");
main.classList.remove("bg-two");
} else if (two_distance < 150 && one_distance < 0) {
main.classList.add("bg-two");
main.classList.remove("bg-one");
} else if (one_distance > 150 && two_distance > 150){
main.classList.add("site-main");
main.classList.remove("bg-two");
main.classList.remove("bg-one");
}
}

How to change an image every 15 seconds in HTML

I have an image in my HTML page, and I would like it to change to a different image every 15 seconds.
<img src="img/img 1.jpg" alt="image">
In my local folder img, I have two images which are img 1.jpg and img 2.jpg. How do I change the img 1.jpg to img 2.jpg after 15 seconds?
Try it:
$(document).ready(function(){
var img = 0;
var slides = new Array();
while (img < 5) {
img++;
// put your image src in sequence
var src = 'assets/images/earth/Sequence' + img + '.jpg';
slides.push(src);
}
var index = 0,timer = 0;
showNextSlide();
timer = setInterval(showNextSlide, 15000);
function showNextSlide() {
if (index >= slides.length) {
index = 0;
}
document.getElementById('earth').src = slides[index++];
}
});
Try this (pure JS)
var myArray = ['img1', 'img2', 'img3', 'img4', 'img5', 'img6']
var count = 0;
setInterval(function() {
//use this below line if you want random images
//var rand = myArray[Math.floor(Math.random() * myArray.length)];
if (count >= myArray.length) count = 0; // if it is last image then show the first image.
// use this below line if you want images in order.
var rand = myArray[count];
document.getElementById('img').src = rand;
document.getElementById('img').alt = rand; // use 'alt' to display the image name if image is not found
count++;
}, 1000); // 1000 = 1 second
<img src="img/img 1.jpg" alt="image" id='img' />
To do this, you're going to need some Javascript to change the image. Here is a link to a popular website for help with Javascript, HTML, CSS, and a whole lot more. What you'll want to be looking at specifically though, is the setInterval() function on this page: http://www.w3schools.com/js/js_timing.asp
If you don't know Javascript at all, it is also not a bad place to start learning! If that's all you need it for though, you'll need very little Javascript at all.
Firstly include jQuery library in your page.
Then use this script:
$(document).ready(function() {
setInterval(function(){
_path = $('img').attr('src');
_img_id = _path.replace('img/img', '');
_img_id = _img_id.replace('.jpg', '');
_img_id++;
if (_img_id == 3) {
_img_id = 1;
};
$('img').attr('src', 'img/img' + _img_id + '.jpg');
}, 15000);
});

Is possible create map html area in percentage?

I need to create something like this:
http://www.mrporter.com/journal/journal_issue71/2#2
where every product in my big image is associated with a tooltip which appears on mouse hover.
But I need this to work with fullscreen images.
The first solution I thought (as the example above) is the map html solution where each fill up exactly the boundaries of my products.
The problem is that I can't indicate precise values for my because my image size depends on window screen.
The best solution would be the possibility to set percentage values for my area.
Is this possible? Any other suggestions ?
Alternative solution using links:
CSS:
.image{
position: relative;
}
.image a{
display: block;
position: absolute;
}
HTML:
<div class="image">
<img src="image.jpg" alt="image" />
</div>
Percentage dimensions can be detected in graphic editors
There is a jQuery plugin for this jQuery RWD Image Maps.
You might want to integrate my pending pull request (manually) to support "width=100%": https://github.com/stowball/jQuery-rwdImageMaps/pull/10
you can check this this plugin is life saving.
Useful when you want to map a percentage scaled image etc.
It can be used with or without jQuery.
https://github.com/davidjbradshaw/imagemap-resizer
and you can see it working at.
http://davidjbradshaw.com/imagemap-resizer/example/
Because this can't be done with simple HTML/CSS manipulation, the only alternative is JavaScript to, effectively, recalculate the coordinates based on the resizing of the image. To this end I've put together a function (though there's two functions involved) that achieves this end:
function findSizes(el, src) {
if (!el || !src) {
return false;
}
else {
var wGCS = window.getComputedStyle,
pI = parseInt,
dimensions = {};
dimensions.actualWidth = pI(wGCS(el, null).width.replace('px', ''), 10);
var newImg = document.createElement('img');
newImg.src = src;
newImg.style.position = 'absolute';
newImg.style.left = '-10000px';
document.body.appendChild(newImg);
dimensions.originalWidth = newImg.width;
document.body.removeChild(newImg);
return dimensions;
}
}
function remap(imgElem) {
if (!imgElem) {
return false;
}
else {
var mapName = imgElem
.getAttribute('usemap')
.substring(1),
map = document.getElementsByName(mapName)[0],
areas = map.getElementsByTagName('area'),
imgSrc = imgElem.src,
sizes = findSizes(imgElem, imgSrc),
currentWidth = sizes.actualWidth,
originalWidth = sizes.originalWidth,
multiplier = currentWidth / originalWidth,
newCoords;
for (var i = 0, len = areas.length; i < len; i++) {
newCoords = areas[i]
.getAttribute('coords')
.replace(/(\d+)/g,function(a){
return Math.round(a * multiplier);
});
areas[i].setAttribute('coords',newCoords);
}
}
}
var imgElement = document.getElementsByTagName('img')[0];
remap(imgElement);​
JS Fiddle demo.
Please note, though, that this requires a browser that implements window.getComputedStyle() (most current browsers, but only in IE from version 9, and above). Also, there are no sanity checks other than ensuring the required arguments are passed into the functions. These should, though, be a start if you want to experiment.
References:
document.body.
document.createElement().
document.getElementsByName().
document.getElementsByTagName().
element.getAttribute().
element.setAttribute().
element.style.
Math.round().
node.appendChild().
node.removeChild().
parseInt().
string.replace().
string.substring().
window.getComputedStyle.
Percentages in image maps are not an option. You might want to get some scripting involved (JS) that recalculates the exact position on images resize. Of course, in that script you can work with percentages if you want.
Consider using the Raphaël JavaScript Library with some CSS. See http://raphaeljs.com/ and Drawing over an image using Raphael.js.
I know this is an old question but maybe someone needs this at some point as I did. I modified #David Thomas' answer a bit to be have this little piece of JS be able to handle future recalculations:
function findSizes(el, src) {
if (!el || !src) {
return false;
}
else {
var wGCS = window.getComputedStyle,
pI = parseInt,
dimensions = {};
dimensions.actualWidth = pI(wGCS(el, null).width.replace('px', ''), 10);
var newImg = document.createElement('img');
newImg.src = src;
newImg.style.position = 'absolute';
newImg.style.left = '-10000px';
document.body.appendChild(newImg);
dimensions.originalWidth = newImg.width;
document.body.removeChild(newImg);
return dimensions;
}
}
function remap(imgElem) {
if (!imgElem) {
return false;
}
else {
var mapName = imgElem
.getAttribute('usemap')
.substring(1),
map = document.getElementsByName(mapName)[0],
areas = map.getElementsByTagName('area'),
imgSrc = imgElem.src,
sizes = findSizes(imgElem, imgSrc),
currentWidth = sizes.actualWidth,
originalWidth = sizes.originalWidth,
multiplier = currentWidth / originalWidth,
newCoords;
for (var i = 0, len = areas.length; i < len; i++) {
// Save original coordinates for future use
var originalCoords = areas[i].getAttribute('data-original-coords');
if (originalCoords == undefined) {
originalCoords = areas[i].getAttribute('coords');
areas[i].setAttribute('data-original-coords', originalCoords);
}
newCoords = originalCoords.replace(/(\d+)/g,function(a){
return Math.round(a * multiplier);
});
areas[i].setAttribute('coords',newCoords);
}
}
}
function remapImage() {
var imgElement = document.getElementsByTagName('img')[0];
remap(imgElement);
}
// Add a window resize event listener
var addEvent = function(object, type, callback) {
if (object == null || typeof(object) == 'undefined') return;
if (object.addEventListener) {
object.addEventListener(type, callback, false);
} else if (object.attachEvent) {
object.attachEvent("on" + type, callback);
} else {
object["on"+type] = callback;
}
};
addEvent(window, "resize", remapImage);

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

According to the Apple iOS mantra it should be possible to scroll the contents of an IFRAME by dragging it with two fingers. Unfortunately running the latest version of iOS on the iPad I have yet to find a single website with an IFRAME that scrolls using this method - no scrollbars appear either.
Does anyone know how a user is supposed to scroll the contents of an IFRAME with the mobile Safari?
iOS 5 added the following style that can be added to the parent div so that scrolling works.
-webkit-overflow-scrolling:touch
-webkit-overflow-scrolling:touch as mentioned in the answer is infact the possible solution.
<div style="overflow:scroll !important; -webkit-overflow-scrolling:touch !important;">
<iframe src="YOUR_PAGE_URL" width="600" height="400"></iframe>
</div>
But if you are unable to scroll up and down inside the iframe as shown in image below,
you could try scrolling with 2 fingers diagonally like this,
This actually worked in my case, so just sharing it if you haven't still found a solution for this.
It doesn't appear that iframes display and scroll properly. You can use an object tag to replace an iframe and the contents will be scrollable with 2 fingers. Here's a simple example:
<html>
<head>
<meta name="viewport" content="minimum-scale=1.0; maximum-scale=1.0; user-scalable=false; initial-scale=1.0;"/>
</head>
<body>
<div>HEADER - use 2 fingers to scroll contents:</div>
<div id="scrollee" style="height:75%;" >
<object id="object" height="90%" width="100%" type="text/html" data="http://en.wikipedia.org/"></object>
</div>
<div>FOOTER</div>
</body>
</html>
This is not my answer, but I just copied it from https://gist.github.com/anonymous/2388015 just because the answer is awesome and fixes the problem completely. Credit completely goes to the anonymous author.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
if (/iPhone|iPod|iPad/.test(navigator.userAgent))
$('iframe').wrap(function(){
var $this = $(this);
return $('<div />').css({
width: $this.attr('width'),
height: $this.attr('height'),
overflow: 'auto',
'-webkit-overflow-scrolling': 'touch'
});
});
})
</script>
As mentioned in other posts, the combination of css values of overflow: auto; &
-webkit-overflow-scrolling: touch;
works when applied to BOTH the iframe in question AND its parent div
With the unfortunate side-effect of double scrollbars on non-touch browsers.
The solution I used was to add these css values via javascript/jquery. Which allowed me to use a base css for all browsers
if (isSafariBrowser()){
$('#parentDivID').css('overflow', 'auto');
$('#parentDivID').css('-webkit-overflow-scrolling', 'touch');
$('#iframeID').css('overflow', 'auto');
$('#iframeID').css('-webkit-overflow-scrolling', 'touch');
}
where isSafariBrowser() is defined as foll...
var is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
var is_safari = navigator.userAgent.indexOf("Safari") > -1;
function isSafariBrowser(){
if (is_safari){
if (is_chrome) // Chrome seems to have both Chrome and Safari userAgents
return false;
else
return true;
}
return false;
}
This allowed my application to work on an iPad
Note
1) Not tested on other ios systems
2) Not tested this on Android browsers on tablets, may need additional changes
(so this solution may not be complete)
The code below works for me (thanks to Christopher Zimmermann for his blog post http://dev.magnolia-cms.com/blog/2012/05/strategies-for-the-iframe-on-the-ipad-problem/). The problems are:
There are no scroll bars to let the user know that they can scroll
Users have to use two-finger scrolling
The PDF files are not centered (still working on it)
<!DOCTYPE HTML>
<html>
<head>
<title>Testing iFrames on iPad</title>
<style>
div {
border: solid 1px green;
height:100px;
}
.scroller{
border:solid 1px #66AA66;
height: 400px;
width: 400px;
overflow: auto;
text-align:center;
}
</style>
<table>
<tr>
<td><div class="scroller">
<iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
</div>
</td>
<td><div class="scroller">
<iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
</div>
</td>
</tr>
<tr>
<td><div class="scroller">
<iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
</div>
</td>
<td><div class="scroller">
<iframe width="400" height="400" src="http://www.supremecourt.gov/opinions/11pdf/11-393c3a2.pdf" ></iframe>
</div>
</td>
</tr>
</table>
<div> Here are some additional contents.</div>
This is what I did to get iframe scrolling to work on iPad. Note that this solution only works if you control the html that is displayed inside the iframe.
It actually turns off the default iframe scrolling, and instead causes the body tag inside the iframe to scroll.
main.html:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#container {
position: absolute;
top: 50px;
left: 50px;
width: 400px;
height: 300px;
overflow: hidden;
}
#iframe {
width: 400px;
height: 300px;
}
</style>
</head>
<body>
<div id="container">
<iframe src="test.html" id="iframe" scrolling="no"></iframe>
</div>
</body>
</html>
test.html:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html {
overflow: auto;
-webkit-overflow-scrolling: touch;
}
body {
height: 100%;
overflow: auto;
-webkit-overflow-scrolling: touch;
margin: 0;
padding: 8px;
}
</style>
</head>
<body>
…
</body>
</html>
The same could probably be accomplished using jQuery if you prefer:
$("#iframe").contents().find("body").css({
"height": "100%",
"overflow": "auto",
"-webkit-overflow-scrolling": "touch"
});
I used this solution to get TinyMCE (wordpress editor) to scroll properly on the iPad.
Based on this article, I have put together the following snippet that provides some very basic functionality:
<div id = "container"></div>
<script>
function setPDFHeight(){
$("#pdfObject")[0].height = $("#pdfObject")[0].offsetHeight;
}
$('#container').append('<div align="center" style="width: 100%; height:100%; overflow: auto !important; -webkit-overflow-scrolling: touch !important;">\
<object id="pdfObject" width="100%" height="1000000000000" align="center" data="content/lessons/12/t.pdf" type="application/pdf" onload="setPDFHeight()">You have no plugin installed</object></div>');
</script>
Obviously it is far from perfect (given that it practically expands your page height to infinity), but it's the only viable workaround I've found so far.
None of the solutions so far completely worked for me when I tried (sometimes, only buggy on secondary loads), but as a workaround, using an object element as described here, then wrapping in a scrollable div, then setting the object to a very high height (5000px) did the job for me. It's a big workaround and doesn't work incredibly well (for starters, pages over 5000px would cause issues -- 10000px completely broke it for me though) but it seems to get the job done in some of my test cases:
var style = 'left: ...px; top: ...px; ' +
'width: ...px; height: ...px; border: ...';
if (isIOs) {
style += '; overflow: scroll !important; -webkit-overflow-scrolling: touch !important;';
html = '<div style="' + style + '">' +
'<object type="text/html" data="http://example.com" ' +
'style="width: 100%; height: 5000px;"></object>' +
'</div>';
}
else {
style += '; overflow: auto;';
html = '<iframe src="http://example.com" ' +
'style="' + style + '"></iframe>';
}
Here's hoping Apple will fix the Safari iFrame issues.
The Problem
I help maintain a big, complicated, messy old site in which everything (literally) is nested in multiple levels of iframes-- many of which are dynamically created and/or have a dynamic src. That creates the following challenges:
Any changes to the HTML structure risk breaking scripts and stylesheets that haven't been touched in years.
Finding and fixing all of the iframes and src documents manually would take way too much time and effort.
Of the solutions posted so far, this is the only one I've seen that overcomes challenge 1. Unfortunately, it doesn't seem to work on some iframes, and when it does, the scrolling is very glitchy (which seems to cause other bugs on the page, such as unresponsive links and form controls).
The Solution
If the above sounds anything like your situation, you may want to give the following script a try. It forgoes native scrolling and instead makes all iframes draggable within the bounds of their viewport. You only need to add it to the document that contains the top level iframes; it will apply the fix as needed to them and their descendants.
Here's a working fiddle*, and here's the code:
(function() {
var mouse = false //Set mouse=true to enable mouse support
, iOS = /iPad|iPhone|iPod/.test(navigator.platform);
if(mouse || iOS) {
(function() {
var currentFrame
, startEvent, moveEvent, endEvent
, screenY, translateY, minY, maxY
, matrixPrefix, matrixSuffix
, matrixRegex = /(.*([\.\d-]+, ?){5,13})([\.\d-]+)(.*)/
, min = Math.min, max = Math.max
, topWin = window;
if(!iOS) {
startEvent = 'mousedown';
moveEvent = 'mousemove';
endEvent = 'mouseup';
}
else {
startEvent = 'touchstart';
moveEvent = 'touchmove';
endEvent = 'touchend';
}
setInterval(scrollFix, 500);
function scrollFix() {fixSubframes(topWin.frames);}
function fixSubframes(wins) {for(var i = wins.length; i; addListeners(wins[--i]));}
function addListeners(win) {
try {
var doc = win.document;
if(!doc.draggableframe) {
win.addEventListener('unload', resetFrame);
doc.draggableframe = true;
doc.addEventListener(startEvent, touchStart);
doc.addEventListener(moveEvent, touchMove);
doc.addEventListener(endEvent, touchEnd);
}
fixSubframes(win.frames);
}
catch(e) {}
}
function resetFrame(e) {
var doc = e.target
, win = doc.defaultView
, iframe = win.frameElement
, style = getComputedStyle(iframe).transform;
if(iframe===currentFrame) currentFrame = null;
win.removeEventListener('unload', resetFrame);
doc.removeEventListener(startEvent, touchStart);
doc.removeEventListener(moveEvent, touchMove);
doc.removeEventListener(endEvent, touchEnd);
if(style !== 'none') {
style = style.replace(matrixRegex, '$1|$3|$4').split('|');
iframe.style.transform = style[0] + 0 + style[2];
}
else iframe.style.transform = null;
iframe.style.WebkitClipPath = null;
iframe.style.clipPath = null;
delete doc.draggableiframe;
}
function touchStart(e) {
var iframe, style, offset, coords
, touch = e.touches ? e.touches[0] : e
, elem = touch.target
, tag = elem.tagName;
currentFrame = null;
if(tag==='TEXTAREA' || tag==='SELECT' || tag==='HTML') return;
for(;elem.parentElement; elem = elem.parentElement) {
if(elem.scrollHeight > elem.clientHeight) {
style = getComputedStyle(elem).overflowY;
if(style==='auto' || style==='scroll') return;
}
}
elem = elem.ownerDocument.body;
iframe = elem.ownerDocument.defaultView.frameElement;
coords = getComputedViewportY(elem.clientHeight < iframe.clientHeight ? elem : iframe);
if(coords.elemTop >= coords.top && coords.elemBottom <= coords.bottom) return;
style = getComputedStyle(iframe).transform;
if(style !== 'none') {
style = style.replace(matrixRegex, '$1|$3|$4').split('|');
matrixPrefix = style[0];
matrixSuffix = style[2];
offset = parseFloat(style[1]);
}
else {
matrixPrefix = 'matrix(1, 0, 0, 1, 0, ';
matrixSuffix = ')';
offset = 0;
}
translateY = offset;
minY = min(0, offset - (coords.elemBottom - coords.bottom));
maxY = max(0, offset + (coords.top - coords.elemTop));
screenY = touch.screenY;
currentFrame = iframe;
}
function touchMove(e) {
var touch, style;
if(currentFrame) {
touch = e.touches ? e.touches[0] : e;
style = min(maxY, max(minY, translateY + (touch.screenY - screenY)));
if(style===translateY) return;
e.preventDefault();
currentFrame.contentWindow.getSelection().removeAllRanges();
translateY = style;
currentFrame.style.transform = matrixPrefix + style + matrixSuffix;
style = 'inset(' + (-style) + 'px 0px ' + style + 'px 0px)';
currentFrame.style.WebkitClipPath = style;
currentFrame.style.clipPath = style;
screenY = touch.screenY;
}
}
function touchEnd() {currentFrame = null;}
function getComputedViewportY(elem) {
var style, offset
, doc = elem.ownerDocument
, bod = doc.body
, elemTop = elem.getBoundingClientRect().top + elem.clientTop
, elemBottom = elem.clientHeight
, viewportTop = elemTop
, viewportBottom = elemBottom + elemTop
, position = getComputedStyle(elem).position;
try {
while(true) {
if(elem === bod || position === 'fixed') {
if(doc.defaultView.frameElement) {
elem = doc.defaultView.frameElement;
position = getComputedStyle(elem).position;
offset = elem.getBoundingClientRect().top + elem.clientTop;
viewportTop += offset;
viewportBottom = min(viewportBottom + offset, elem.clientHeight + offset);
elemTop += offset;
doc = elem.ownerDocument;
bod = doc.body;
continue;
}
else break;
}
else {
if(position === 'absolute') {
elem = elem.offsetParent;
style = getComputedStyle(elem);
position = style.position;
if(position === 'static') continue;
}
else {
elem = elem.parentElement;
style = getComputedStyle(elem);
position = style.position;
}
if(style.overflowY !== 'visible') {
offset = elem.getBoundingClientRect().top + elem.clientTop;
viewportTop = max(viewportTop, offset);
viewportBottom = min(viewportBottom, elem.clientHeight + offset);
}
}
}
}
catch(e) {}
return {
top: max(viewportTop, 0)
,bottom: min(viewportBottom, doc.defaultView.innerHeight)
,elemTop: elemTop
,elemBottom: elemBottom + elemTop
};
}
})();
}
})();
* The jsfiddle has mouse support enabled for testing purposes. On a production site, you'd want to set mouse=false.
After much aggravation, I discovered how to scroll in iframes on my ipad. The secret was to do a vertical finger swipe (single finger was fine) on the LEFT side of the iframe area (and maybe slightly outside of the border). On a laptop or PC, the scroll bar is on the right, so naturally, I spent of lot of time on my ipad experimenting with finger motions on the right side. Only when I tried the left side would the iframe scroll.
Add overflow: auto; to the style and the two finger scroll should work.