Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialEina Onting
Courses Plus Student 3,266 PointsAutofocus on Edit Input Field
I'm trying to get the edit field to autofocus whenever you click edit, meaning that the text cursor is automatically on that field and it's focused on for accessibility and stuff.
This is the code I currently have in my editTask function:
var hasClassEditMode = listItem.classList.contains('editMode');
if(hasClassEditMode){
//switch from .editMode
//label text become's input value
label.innerText = editInput.value;
editButton.innerText = 'Edit';
editInput.autofocus = false;
}else {
//else
//switch to .editMode
//input value becomes the label's text
editInput.value = label.innerText;
editButton.innerText = 'Save';
editInput.autofocus = true;
}
Here's a fiddle for it. When you click edit for the first time, it should autofocus on the input but the next time you click edit it only focuses on the element? I tried removing it after the user hits save but it's not really doing what I want it to do.
I think I'm approaching this wrong, but any help would be appreciated.
2 Answers
Andrew VanVlack
20,155 PointsAutofocus property is best designed on page loads, focusable DOM items do have focus and blur (unfocus) functions though. It is a bit fussy so it works best inside a time out:
if(hasClassEditMode){
//switch from .editMode
//label text become's input value
label.innerText = editInput.value;
editButton.innerText = 'Edit';
}else {
//else
//switch to .editMode
//input value becomes the label's text
editInput.value = label.innerText;
editButton.innerText = 'Save';
window.setTimeout(function () {
editInput.focus();
}, 0);
michaelkyllo
11,330 PointsHi Eina, I have one question about this project.
Is the editInput value supposed to be established? I am never seeing
label.innerText = editInput.value;
happen? I'm not sure what I'm missing. Thanks,
Eina Onting
Courses Plus Student 3,266 PointsEina Onting
Courses Plus Student 3,266 PointsThank you, that worked like a charm!