I made a page with multiple elements that use the contenteditable
property. I added the functionality that when you tab to the next element, the text is auto-selected (using a little plug-in I found on this answer).
But then if you tabbed to an element that was off the screen, the window didn't auto-scroll to show the element (at least in Chrome). So I used the focus
event and .animate()
to jump to the element.
And now my issue is that I don't want to jump to the element if it is clicked on instead of tabbed to. It gets annoying when the element is already in view, but then jumps to the top of the page when you click on it. Here is a fiddle to look at.
This is the code I'm using:
$.fn.selectText = function(){
var doc = document;
var element = this[0];
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
$(document).on('focus', '.content', function(e) {
var top = $(this).offset().top - 100;
$(this).selectText();
$('body').animate({
scrollTop: top
}, 25);
return true;
});
I've tried using stopPropagation()
and preventDefault()
and changing around the binding order but to no avail. What's the best way to ignore this focus event on click but not on tab? Or is there a way to restore the original auto-scroll functionality?