Search code examples
javascriptarraysinputthisselectors-api

Alternative to This in Javascript


I have this code on codepen: https://codepen.io/RaoniSousa/pen/Zpkxbb:

var x = document.querySelectorAll('.label'), //label com ID label,
    z = document.querySelectorAll('.input'); //input com ID name;

function myFunction() {
'use strict';
if (this.value !== "" ) {
    this.style.opacity = '1';
    this.style.bottom = '4em';
    this.style.color = '#722872';
    console.log(this);
} else {
    this.style.opacity = '0';
    this.style.bottom = '1.5em';
    console.log(this);
    }
}

In the function above i'd like to change only the style of the label (var x). I know the 'this' is referring to .input (var z), but, i'd like to apply a style to label as i change his related input value, but if i use a for loop, he calls all label one the same time. Is there a way to call var x intead of var z by using 'this.style' or somebody knows another alternative to this code?

I'd like it works as happens here(roll down the bar till reach Contact Me section): https://codepen.io/freeCodeCamp/pen/YqLyXB

Thanks in advance.


Solution

  • try this

    function myFunction() {
        'use strict';
        if (this.value !== "" ) {
            this.nextElementSibling.style.opacity = '1';
            this.nextElementSibling.style.bottom = '2em';
            this.nextElementSibling.style.color = '#722872';
            console.log(this.nextElementSibling);
        } else {
            this.style.opacity = '.4';
            this.style.bottom = '.5em';
            console.log(this);
        }
    }