Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Add event listener on element focus

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #254544
    svoltmer
    Participant

    I have a search box input that opens when an icon is clicked on. I would like to give the input focus when the icon is clicked and call the function addLabel() that adds a label as placeholder text until a “onkeydown” event is fired, at which time it should call the function removeLabel(). Currently, my script adds focus(), but doesn’t acknowledge the other event listeners. Any help would be appreciated!

     window.onload = function() {
    
    <!-- create absolutly positioned label as placeholder text for search -->
            var el = document.getElementById('gsc-i-id1');
            var label = document.createElement('label');
            var labelText = document.createTextNode('Enter your search term...');
            label.appendChild(labelText);
            label.className += 'search-label-placeholder';
            var searchParent = el.parentNode;
            searchParent.insertBefore(label, el);
    
            var searchIcon = document.getElementById('search-icon');
            searchIcon.addEventListener('click', function(e) {
    
                el.addEventListener('focus', addLabel );
                el.addEventListener('keydown', removeLabel );
                el.focus();
            }, false );
    
               function removeLabel() {
    
                el.style.textIndent = '0';
                el.setAttribute('placeholder', 'removeLabel');
                el.style.background = 'none';
                el.style.textIndent = '0';
                label.style.display = 'none';
               };
               function addLabel() {
    
                el.style.textIndent = '0';
                el.setAttribute('placeholder', 'addLabel');
                el.style.background = 'none';
                el.style.textIndent = '0';
                label.style.display = 'block';
                };
            };
    
    #254762
    processprocess
    Participant

    Hey svoltmer,

    I think we can simplify this.
    I wrote you a demo based on what I think you’re going for.
    Check it out:

    https://codepen.io/philipbell/pen/pPLQeK

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.