Skip to content

Instantly share code, notes, and snippets.

@michimani
Created February 6, 2019 01:45
Show Gist options
  • Save michimani/b5dc7d6b40fc4f31ee3e93e30bcdfc39 to your computer and use it in GitHub Desktop.
Save michimani/b5dc7d6b40fc4f31ee3e93e30bcdfc39 to your computer and use it in GitHub Desktop.
Add overlay to a word separated by whitespace inputted at a textbox.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Textbox Overlay Style by White Space</title>
<style type="text/css">
#overlay-sample {
margin: 30px;
font-family: inherit;
}
#overlay-area {
color: transparent;
letter-spacing: .02em;
margin: 2px;
overflow-wrap: break-word;
overflow: hidden;
padding: 6px 12px;
position: absolute;
white-space: pre-wrap;
width: 100%;
font-size: 16px !important;
}
#overlay-area span.overlay {
background-color: #b2dfdb;
border-radius: 2px;
box-shadow: 0 0 0 1px #80cbc4;
padding-bottom: 1px;
padding-top: 1px;
}
#overlay-textbox-area input[type=text] {
background: transparent;
font-family: inherit;
font-size: 16px !important;
letter-spacing: .02em;
outline: 0px;
padding: 6px 12px;
position: relative;
width: 100%;
}
</style>
</head>
<body>
<div id="overlay-sample">
<div id="overlay-textbox-area">
<div id="overlay-area"></div>
<input type="text" autocomplete="off">
</div>
</div>
<script type="text/javascript">
const textElem = document.querySelector('#overlay-textbox-area input[type=text]');
textElem.addEventListener('keyup', (event) => {
renderOverLay(event.target.value);
});
function renderOverLay(text) {
const overlayArea = document.getElementById('overlay-area');
const charPartsList = text.split(' ');
let spanSource = '';
for (let i = 0; i < charPartsList.length; i++) {
if (spanSource !== '' && !spanSource.match(/ $/)) {
spanSource += ' ';
}
if (charPartsList[i] === '') {
spanSource += ' ';
} else {
spanSource += `<span class="overlay">${charPartsList[i]}</span>`;
}
}
overlayArea.innerHTML = spanSource;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment