Reputation: 2897
Okay, I am trying to do something, but I am clearly doing it wrong.
I have this function in JS:
function onFocus() {
document.getElementsByClassName('blur').classList.add("blurry");
}
function onFocusOut() {
document.getElementsByClassName('blur').classList.remove("blurry");
}
The error I ge, is as follows:
Uncaught TypeError: Cannot read property 'add' of undefined
What I try to do, is to get all elements with the classname blur and add another classname (blurry) to it... yet this doesn't work, because my CSS is not being changed.
The only thing I want to achieve, is to add opacity to the elements with that classname when an input field is clicked / focused and to remove it when someone clicks outside of the input field.
.blurry {
opacity: 0.4
}
PS: initially, I started using id's
instead of classes
, but that would mean that I can use this function just on one HTML elements. That's why I decided to switch to classnames.
Upvotes: 0
Views: 66
Reputation: 1515
To maintain that format you're going for, you can simply add a for
loop to iterate through all of the elements with the class name "blur".
I've added an example of a way to implement a for
loop in your case:
function onFocus() {
var blurElements = document.getElementsByClassName('blur');
for (var i = 0, l = blurElements.length; i < l; i++) {
blurElements[i].classList.add("blurry");
}
}
function onFocusOut() {
var blurElements = document.getElementsByClassName('blur');
for (var i = 0, l = blurElements.length; i < l; i++) {
blurElements[i].classList.remove("blurry");
}
}
Upvotes: 2