DEV Community

StuartCreed
StuartCreed

Posted on • Updated on

Create a search bar spotlight modal with JS

buildSearchSpotlight() {
        this.spotlightModal = document.createElement('DIV');
        this.spotlightModal.setAttribute('id', 'spotlightModal')
        this.spotlightModal.classList.add('hidden');
        this.searchBar = document.createElement('INPUT');
        this.searchBar.setAttribute('id', 'search-box')
        this.searchbarWrapper = document.createElement('DIV');
        this.searchbarWrapper.appendChild(this.searchBar)
        this.spotlightModal.appendChild(this.searchbarWrapper);

        // Add styling
        this.spotlightModal.style.position = 'absolute'
        this.spotlightModal.style.width = '100vw'
        this.spotlightModal.style.height = '100vh'
        this.spotlightModal.style.left = '0'
        this.spotlightModal.style.top = '0'
        this.spotlightModal.style.backgroundColor = 'rgba(0, 0, 0, 0.2)'
        this.spotlightModal.style.display = 'flex'
        this.spotlightModal.style.justifyContent = 'center'
        this.spotlightModal.style.padding = '40px'

        this.searchBar.style.height = '50px'
        this.searchBar.style.width = '600px'
        this.searchBar.style.borderRadius = '10px'

        document.body.appendChild(this.spotlightModal);

        // Add event listeners
        this.spotlightInitiator.addEventListener('click', e => {
            this.toggleSpotlight()
        })

        this.spotlightModal.addEventListener('click', e => {
            this.toggleSpotlight()
        })

        // Stop the clicking of the search bar closing the modal
        this.searchBar.addEventListener('click', e => {
            e.stopPropagation()
        })
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)