How can we decrease these codes

document.getElementById("input1").addEventListener("focus",focusfunction);

document.getElementById("input1").addEventListener("blur",blurfunction);

function focusfunction(){

    document.getElementById("input1").style.backgroundColor="lime";

}

function blurfunction(){

    document.getElementById("input1").style.backgroundColor="";

}

document.getElementById("input2").addEventListener("focus",focusfunction2);

function focusfunction2(){

    document.getElementById("input2").style.backgroundColor="lime";

}

document.getElementById("input2").addEventListener("blur",blurfunction2);

function blurfunction2(){

    document.getElementById("input2").style.backgroundColor="";

}

If you are going to use an element multiple times you should assign it to a variable, e.g., const ele = document.getElementById("input2")

2 Likes

can we use same function for different input fields ?

Hi @sumitbhandari101, a common principle to try to follow when programming is called DRY: Don’t Repeat Yourself.

Let’s look at the focus function for example.
All it’s doing is taking a dom node and apply a style to it.

Why not generalizing?

function focusFn(node, color="lime") {
   node.style.backgroundColor= color;
}

// example
focusFn(document.getElementById("foo"), "red");
focusFn(document.getElementById("bar"));

This way I can pass whatever node and color I wish.
Hope it helps giving you some idea on how to refactor this :slight_smile:


edit: naming is also something generally considered hard in programming.
For example the above focusFunction is a terrible name (in my opinion) for this function: as a reader I assume that function will do something related with focus, but what it’s doing is changing the background color.
Perhaps something more like updateBackground is a batter name for it :slight_smile:

1 Like