Skip to content

Instantly share code, notes, and snippets.

@justinobney
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save justinobney/29399b270f17f6c6f693 to your computer and use it in GitHub Desktop.

Select an option

Save justinobney/29399b270f17f6c6f693 to your computer and use it in GitHub Desktop.
Adding "Word Break Opportunity" to content.
/*
-- EXAMPLE USES
<div wbr>long.html?var=one$20two</div>
-- With optional regex to override default
<div wbr regex="/(\&|-|\=|(the)|(20))/gi">
long.html?var=one$20two
</div>
*/
(function() {
'use strict';
var app = angular.module('jobneyOrYourModuleName');
app.directive('wbr', function($timeout) {
var whitespace = /^\s*$/;
var defaultRegex = /(\%|\&|-|\=)/gi;
var regexFindingRegex = /^\/[\w|\W]+[\/|g|i]$/gi;
return {
restrict: 'A',
link: function(scope, iElement, iAttr) {
var wbrRegex = iAttr.regex && regexFindingRegex.test(iAttr.regex) ? eval(iAttr.regex) : defaultRegex;
var unwatch = scope.$watch(getStringValue, function(value, previous) {
if (!value)
return;
scope.$evalAsync(function() {
traverse(iElement);
unwatch();
});
});
function traverse(el) {
angular.forEach(el.contents(), function(child) {
var $child = angular.element(child);
if (isTextNode(child)) {
var fixedHtml = $child.text().replace(wbrRegex, function(v) {
return '<wbr>' + v
});
$child.wrap('<span style="display: inline-block;"></span>').parent().html(fixedHtml);
}
if ($child.contents().length) {
traverse($child);
}
});
}
function getStringValue() {
return iElement.html();
}
function isTextNode(domEl) {
return domEl.nodeType === 3 && !whitespace.test(domEl.nodeValue);
}
}
}
});
app.filter('wbr', [
'$sce', function ($sce) {
var defaultRegex = /(\%|\&|-|\=|_)/gi;
var regexFindingRegex = /^\/[\w|\W]+[\/|g|i]$/gi;
return function (value, regex) {
var wbrRegex = regex && regexFindingRegex.test(regex) ? eval(regex) : defaultRegex;
var worker = $('<div />');
var fixedHtml = value.replace(wbrRegex, function (v) {
return v + '<wbr>';
});
var wbrHtml = $('<span style="display: inline-block;"></span>').html(fixedHtml);
worker.append(wbrHtml);
return $sce.trustAs('html', worker.html());
}
}
]);
})();
@justinobney
Copy link
Copy Markdown
Author

I hate when urls run off the parent container because of not allowing a word break. I noticed that this did not happen in gmail. Upon investigating, I found that they are inserting a <wbr></wbr> tag.

MDN, https://developer.mozilla.org/en-US/docs/Web/HTML/Element/wbr, explains:

The Word Break Opportunity () HTML element represents a position within text where the browser may optionally break a line, though its line-breaking rules would not otherwise create a break at that location.

See example: http://plnkr.co/edit/M7g8YNVvO7C6XBI3XcWr?p=preview

@justinobney
Copy link
Copy Markdown
Author

I made it more resilient.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment