HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<div class="hashtag-container">
<div class="hashtag-items">
ハッシュタグ
<div class="hashtag">
<input id="input-hashtag" placeholder="#を入力" />
</div>
<div class="hashtag">
<textarea id="textarea-hashtag" placeholder="#を入力"></textarea>
</div>
</div>
</div>
body {
text-align: center;
}
.hashtag {
}
.hashtag-container {
display: flex;
justify-content: center;
padding: 24px;
}
.hashtag-items {
margin: 8px;
}
input {
width: 200px;
margin: 8px auto;
padding: 8px;
}
textarea {
width: 200px;
height: 120px;
padding: 8px;
}
.input-hashtag {
display: block;
font-size: 12px;
padding: 4px 6px;
position: absolute;
background-color: white;
border-radius: 8px;
white-space: nowrap;
width: auto;
z-index: 9999;
}
.hashtag-recommendation {
width: 160px;
list-style: none;
margin: 0;
padding: 4px;
border: 1px solid;
border-radius: 4px;
box-shadow: 1px 1px 1px;
cursor: pointer;
text-align: left;
}
.hashtag-recommendation > li:hover {
content: "";
background-color: #007bff;
color: white;
}
.hashtag-recommendation--active {
background-color: #007bff;
color: white;
}
/**
* テキスト入力内の指定された選択箇所におけるspanの絶対位置のx、y座標を返却
* @param {object} input - 座標を取得する入力要素
* @param {number} selectionPoint - 入力の選択箇所
*/
const getCursorXY = (input, selectionPoint) => {
const {
offsetLeft: inputX,
offsetTop: inputY,
} = input
// 入力のクローンとなるダミー要素を作成
const div = document.createElement('div')
// 入力の計算されたスタイルを取得し、ダミー要素にコピー
const copyStyle = getComputedStyle(input)
for (const prop of copyStyle) {
div.style[prop] = copyStyle[prop]
}
div.style.position = "fixed";
div.style.top = "0px";
div.style.left = "0px";
div.style.opacity = 0;
// <input/>の場合空白を置き換える
const swap = '.'
const inputValue = input.tagName === 'INPUT' ? input.value.replace(/ /g, swap) : input.value
// テキストエリアの選択箇所までのdivの内容を設定する
const textContent = inputValue.substring(0, selectionPoint)
// ダミー要素divのテキストコンテンツを設定
div.textContent = textContent
if (input.tagName === 'TEXTAREA') div.style.height = 'auto'
if (input.tagName === 'INPUT') div.style.width = 'auto'
// span要素を作成してキャレット位置を取得する
const span = document.createElement('span')
span.textContent = inputValue.substring(selectionPoint) || '.'
// ダミー要素にspanマーカーを追加
div.appendChild(span)
// ダミー要素をbodyに追加
document.body.appendChild(div)
const { offsetLeft: spanX, offsetTop: spanY } = span
document.body.removeChild(div)
return {
x: inputX + spanX,
y: inputY + spanY,
}
}
/**
* ユーザーが特定の文字を入力したかどうかに基づいてカスタムUIを表示
* 簡単のため予め決められたリストから選択
* @param {object} e - keypress、keydown、またはkeyupのイベント
*/
const showHashtagList = (e) => {
const {
currentTarget: input,
key,
type: keyType,
} = e
const {
offsetHeight,
offsetLeft,
offsetTop,
offsetWidth,
scrollLeft,
scrollTop,
selectionStart,
value,
} = input
const {
paddingRight,
lineHeight,
fontSize
} = getComputedStyle(input)
const fontSizeNumber = parseInt(fontSize.replace("px", ""))
const setHashtagListPosition = () => {
const { x, y } = getCursorXY(input, selectionStart)
const newTop = Math.min(
y - scrollTop + fontSizeNumber*2,
y + fontSizeNumber*2
)
input.__hashtag_ui.setAttribute('style', `left: ${x}px; top: ${newTop}px`)
}
const removeHashtagUiIfClickOutPosition = evt => {
if (e !== evt && evt.target !== e.target) {
toggleHashtagList(false)
}
}
const createHashtagUi = () => {
const hashtagUi = document.createElement('div')
hashtagUi.classList.add('input-hashtag', 'input-hashtag--visible')
input.__hashtag_ui = hashtagUi
document.body.appendChild(input.__hashtag_ui)
input.__hashtag_ui.addEventListener('click', clickHashtagListItem)
document.addEventListener('click', removeHashtagUiIfClickOutPosition)
setHashtagListPosition();
return hashtagUi
}
const removeHashtagUi = () => {
input.__hashtag_ui.removeEventListener('click', clickHashtagListItem)
document.body.removeChild(input.__hashtag_ui)
document.removeEventListener('click', removeHashtagUiIfClickOutPosition)
input.__hashtag_ui = null
input.__selected_item = null
}
// toggle custom UI on and off
const toggleHashtagList = (flag) => {
if (input.__hashtag_ui) {
removeHashtagUi()
}
if (flag) {
input.__edit_start_position = selectionStart
createHashtagUi()
filterHashtagList()
}
}
/**
* 矢印キーを通じてリスト内の選択項目を切替
* 選択項が存在しない場合は新しい選択項目を作成
* それ以外の場合は、指定された選択方向に基づいて選択項目を更新
* @param {string} dir - 次に選択する要素の兄弟要素の指定
*/
const toggleHashtagListItem = (dir = 'next') => {
const list = input.__hashtag_ui.querySelector('ul')
if (!input.__selected_item) {
input.__selected_item = input.__hashtag_ui.querySelector('li')
input.__selected_item.classList.add('hashtag-recommendation--active')
} else {
input.__selected_item.classList.remove('hashtag-recommendation--active')
let nextActive = input.__selected_item[`${dir}ElementSibling`]
if (!nextActive && dir === 'next') nextActive = list.firstChild
else if (!nextActive) nextActive = list.lastChild
input.__selected_item = nextActive
nextActive.classList.add('hashtag-recommendation--active')
}
}
const filterHashtagList = () => {
const filter = value.slice(input.__edit_start_position + 1, selectionStart).toLowerCase()
const suggestions = ['hoge', 'huga', 'piyo']
const filteredSuggestions = suggestions.filter((entry) => entry.toLowerCase().includes(filter))
const suggestedList = document.createElement('ul')
suggestedList.classList.add('hashtag-recommendation')
filteredSuggestions.forEach((entry) => {
const entryItem = document.createElement('li')
entryItem.textContent = entry
suggestedList.appendChild(entryItem)
})
if (input.__hashtag_ui.firstChild)
input.__hashtag_ui.replaceChild(suggestedList, input.__hashtag_ui.firstChild)
else
input.__hashtag_ui.appendChild(suggestedList)
}
/**
* 選択された値を与えられると、特殊文字を置き換えて選択された値を挿入します
* @param {string} selected - 入力テキストコンテンツに挿入される選択された値
* @param {bool} click - イベントがクリックだったかどうかを定義します
*/
const selectHashtagListItem = (selected, click = false) => {
const start = input.value.slice(0, input.__edit_start_position)
const end = input.value.slice( click ? selectionStart + 1 : selectionStart, input.value.length)
input.value = `${start}#${selected}${end}`
}
/**
* ユーザーがリストをクリックしたときの処理を行います
* @param {event} e - マーカー要素のクリックイベント
*/
const clickHashtagListItem = (e) => {
e.preventDefault()
if (e.target.tagName === 'LI') {
input.focus()
toggleHashtagList(false)
selectHashtagListItem(e.target.textContent, true)
}
}
const previousChar = value.charAt(selectionStart - 1).trim()
if (key === '#' && previousChar === '') {
toggleHashtagList(true)
} else if (input.__hashtag_ui) {
switch(key) {
case 'ArrowUp':
case 'ArrowDown':
if (keyType == "keyup") return
e.preventDefault()
toggleHashtagListItem(key === 'ArrowUp' ? 'previous' : 'next')
break
case 'ArrowLeft':
case 'ArrowRight':
if (keyType == "keyup") {
if (selectionStart < input.__edit_start_position + 1)
toggleHashtagList(false)
}
break
case '#':
case ' ':
if (keyType == "keyup") return
toggleHashtagList(false)
break
case 'Backspace':
if (previousChar == "") {
toggleHashtagList(false)
break
}
filterHashtagList()
break
case 'Enter':
if (input.__selected_item) {
e.preventDefault()
selectHashtagListItem(input.__hashtag_ui.querySelector('.hashtag-recommendation--active').textContent)
}
toggleHashtagList(false)
break
default:
// if (keyType == "keyup") return
filterHashtagList();
break
}
}
}
const getHashtagInputDOM = document.querySelector('#input-hashtag');
const getHashtagTextAreaDOM = document.querySelector('#textarea-hashtag');
getHashtagInputDOM.addEventListener('keydown', showHashtagList);
getHashtagTextAreaDOM.addEventListener('keydown', showHashtagList);
getHashtagInputDOM.addEventListener('keyup', showHashtagList);
getHashtagTextAreaDOM.addEventListener('keyup', showHashtagList);
Also see: Tab Triggers