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 trial
dbrink dbrink
6,258 PointsConfusion with trying to create editable spans.
Hi guys,
I'm trying to create a simple program that will let me edit a span on click and save the edited text from input on blur. I've managed to get it working fine on a single span, but can't seem to figure out how to apply it to any instance of span.
I feel like I'm overlooking something obvious, but can't seem to get a grasp on it. Can anyone give my any help on what I'm doing wrong here?
1 Answer
Steven Parker
243,658 PointsWhen you replace your span with the input box, you lose your reference to it. So you need to create a new one when the text box blurs: Then you need to add a listener to the new one so you can change it again later:
saveIt: function() {
var newspan = document.createElement("span");
newspan.innerHTML = this.value;
document.body.replaceChild(newspan, this);
newspan.addEventListener('click', changeMethods.changeIt);
}
As an alternative, if you used event delegation, you would only need one handler for all the spans, including the newly-created ones.
Also, when establishing your blur handler, remember that "text" is a single element, not an array:
// for (let i = 0; i < text.length; i += 1) { <-- text is NOT an array!
// text[i].addEventListener('blur', changeMethods.saveIt);
// }
text.addEventListener('blur', changeMethods.saveIt);
dbrink dbrink
6,258 Pointsdbrink dbrink
6,258 PointsThis worked perfectly. I haven't messed around much with event delegation, but I'll try and refactor it from here. Thanks for the help!