WP DEV Section 13-17: Search


WordPress

Updated Jul 22nd, 2022

I enjoyed this section.

Work with client side JS modules using @wordpress/scripts build tool.

Open full screen search modal with clicks and keypresses.

Note: e.keycode is deprecated use e.code

Prevent body from scrolling behind the overlay.

Prevent excessive event firing with “isOverlayOpen” state.

Reset the field and focus on open.

Getting errors in the console because “this.searchField” is not in the document when the search is not open. Needed to wrap in conditionals:

typingLogic() {
    if (this.searchField.value != this.previousValue) {
      clearTimeout(this.typingTimer)

      if (this.searchField.value) {
        if (!this.isSpinnerVisible) {
          this.resultsDiv.innerHTML = '<div class="spinner-loader"></div>'
          this.isSpinnerVisible = true
        }
        this.typingTimer = setTimeout(this.getResults.bind(this), 750)
      } else {
        this.resultsDiv.innerHTML = ""
        this.isSpinnerVisible = false
      }
    }

    this.previousValue = this.searchField.value
  }
openOverlay() {
    this.searchOverlay.classList.add("search-overlay--active")
    document.body.classList.add("body-no-scroll")
    if (this.searchField) {
      this.searchField.value = ""
      setTimeout(() => this.searchField.focus(), 301)
    }

    this.isOverlayOpen = true
  }

Prevent a user hitting the “S Key” on another input, somewhere else on the site, and accidentally opening the search:

keyPressDispatcher(e) {
    if (e.code == "KeyS" && this.isOverlayOpen == false && document.activeElement.tagName != "INPUT" && document.activeElement.tagName != "TEXTAREA") {
      this.openOverlay()
    }
    if (e.code == "Escape" && this.isOverlayOpen == true) {
      this.closeOverlay()
    }
  }