Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

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.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

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.

+ add another resource

Packages

Add Packages

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.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <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>

              
            
!

CSS

              
                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;
}
              
            
!

JS

              
                /**
  * テキスト入力内の指定された選択箇所における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);
              
            
!
999px

Console