Home › Forums › JavaScript › Add event listener on element focus
- This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
-
AuthorPosts
-
May 5, 2017 at 9:26 am #254544svoltmerParticipant
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'; }; };
May 11, 2017 at 4:22 pm #254762processprocessParticipantHey svoltmer,
I think we can simplify this.
I wrote you a demo based on what I think you’re going for.
Check it out: -
AuthorPosts
Viewing 2 posts - 1 through 2 (of 2 total)
- The forum ‘JavaScript’ is closed to new topics and replies.