This unique solution was inspired by the brilliant @Julian D. and his amazing hack. Although not flawless, it addresses the issue of weird flickering caused by opacity switching during certain points.
body {
overflow: hidden;
}
.wrap {
width: 70%;
margin: 0 auto;
overflow: hidden;
}
.wrap .item {
position: absolute;
white-space: nowrap;
left: 70%;
top: 50%;
background: rgba(20, 20, 20, .5);
color: white;
padding: 10px 15px;
display: inline-block;
max-width: 60px;
}
img {
width: 100%;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
var editableElement = $('#editable'), clonedElement;
// Revert any scrolling
editableElement.on("scroll", function(event) {
editableElement.scrollTop(0);
// Try to prevent scrolling completely (doesn't seem to work)
event.preventDefault();
return false;
});
// Switch overflow visibility on and off again on each keystroke.
// To avoid flickering, a cloned element is positioned below the input
// and switched on while we hide the overflowing element.
editableElement.on("keydown", function() {
// Create a cloned input element below the original one
if (!clonedElement) {
var zIndex = editableElement.css('zIndex');
if (isNaN(parseInt(zIndex, 10))) {
zIndex = 10;
editableElement.css({zIndex: zIndex});
}
clonedElement = editableElement.clone();
clonedElement.css({
zIndex: zIndex-1,
position: 'absolute',
top: editableElement.offset().top,
left: editableElement.offset().left,
overflow: 'hidden',
// Set pseudo focus highlighting for webkit
// (needs to be adapted for other browsers)
outline: 'auto 5px -webkit-focus-ring-color'
});
editableElement.before(clonedElement);
} else {
// Update contents of the cloned element from the original one
clonedElement.html(editableElement.html());
}
// Here comes the hack:
// - set overflow visible but hide element via opactity.
// - show cloned element in the meantime
clonedElement.css({opacity: 1});
editableElement.css({overflow: 'visible', opacity: 0});
// Immediately turn of overflow and show element again.
setTimeout(function() {
editableElement.css({overflow: 'hidden', opacity: 1});
clonedElement.css({opacity: 0});
}, 0);
});
});
</script>
<div class="wrap">
<img src="http://placehold.it/350x150"/>
<div id="editable" class="item" contenteditable="true">Write HERE to get very long text and see scroll</div>
</div>