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
  • #254544

    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.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 );
            }, false );
               function removeLabel() {
       = '0';
                el.setAttribute('placeholder', 'removeLabel');
       = 'none';
       = '0';
       = 'none';
               function addLabel() {
       = '0';
                el.setAttribute('placeholder', 'addLabel');
       = 'none';
       = '0';
       = 'block';

    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:

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