I'd like to convert this small script
to a pure vanilla JS
.
$('input, textarea').focus(function() {
$(this).data('placeholder', $(this).attr('placeholder')).attr('placeholder', '');
}).blur(function() {
$(this).attr('placeholder', $(this).data('placeholder'));
});
Thanks to Treast, I'm here at this point... Almost working good:
var elements = document.querySelectorAll('input, textarea');
for(var i = 0; i < elements.length; i++) {
var element = elements[i];
element.addEventListener('focus', function() {
element.setAttribute('data-placeholder', element.getAttribute('placeholder'));
element.setAttribute('placeholder', '');
}),
element.addEventListener('blur', function() {
element.setAttribute('placeholder', element.getAttribute('data-placeholder'));
element.setAttribute('data-placeholder', '');
});
}
Any idea please?
$('input, textarea')
will select ALL input or textarea. With Vanilla, you cannot add an EventListener
on a list of elements, so you need to loop through all elements. And you need to use querySelectorAll
to get the same list. Also, you cannot chain addEventListener
.
So your code will be:
var elements = document.querySelectorAll('input, textarea');
for(var i = 0; i < elements.length; i++) {
var element = elements[i];
element.addEventListener('focus', function() {
this.setAttribute('data-placeholder', this.getAttribute('placeholder'));
this.setAttribute('placeholder', '');
});
element.addEventListener('blur', function() {
this.setAttribute('placeholder', this.getAttribute('data-placeholder'));
this.setAttribute('data-placeholder', '');
});
}
Have a good look at Patrick's comment above about if this is even needed.
--
As for converting your code to vanilla JS, I think the only issue with your Demo 2 is an unclosed Button tag. I'd suggest splitting things up to help readability. Have a look: https://jsfiddle.net/Lebxdrwk/2/
const onFocus = event => {
const element = event.target;
const placeholder = element.getAttribute('placeholder');
element.setAttribute('data-placeholder', placeholder);
element.setAttribute('placeholder', '');
};
const onBlur = event => {
const element = event.target;
const dataPlaceholder = element.getAttribute('data-placeholder');
element.setAttribute('placeholder', dataPlaceholder);
element.setAttribute('data-placeholder', '');
}
const addEventListenersToSwapPlaceholders = element => {
element.addEventListener('focus', onFocus);
element.addEventListener('blur', onBlur);
}
document.querySelectorAll('input, textarea')
.forEach(addEventListenersToSwapPlaceholders);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.