Home > front end >  Fade on Checkbox for Multiple Div Sections
Fade on Checkbox for Multiple Div Sections

Time:11-30

I have a client that wants to have a checkbox that says "Mark as Compete" and once marked it makes the div with content fade. They basically want a step by step list like a recipe where users can check the box when they are done with a step and have it fade out.

I have been able to do so but not in a friendly way that someone who doesn't know code would be comfortable with editing. I am looking for some help simplifying it.

Current Code:

function ShowHideDivOne(chk_one) {
        var one = document.getElementById("one");
        one.style.opacity = chk_one.checked ? "0.5" : "1";
}
function ShowHideDivTwo(chk_two) {
        var two = document.getElementById("two");
        two.style.opacity = chk_two.checked ? "0.5" : "1";
}
function ShowHideDivThree(chk_three) {
        var three = document.getElementById("three");
        three.style.opacity = chk_three.checked ? "0.5" : "1";
}
div {font-wieght:bold;font-size:30px; margin-top:30px;}
<div id="one">One</div>
<input type="checkbox" id="chk_one" onclick="ShowHideDivOne(this)"/>Mark as done

<div id="two">Two</div>
<input type="checkbox" id="chk_two" onclick="ShowHideDivTwo(this)"/>Mark as done

<div id="three">Three</div>
<input type="checkbox" id="chk_three" onclick="ShowHideDivThree(this)"/>Mark as done

Right now if they wanted to add a "Four," I would have to have the ShowHideDivFour(chk_four) function preprogrammed and then they would have to go in and change all of the ids and onclicks in the div and the checkbox.

I am ok with showing them how to edit the id in the div. What I would prefer is to have a JavaScript code that works for an unlimited number of items in their list and they would only have to change the div id. I understand if they would also have to change the checkbox code but it would be preferable if they didn't.

Any help would be much appreciated.

CodePudding user response:

If, somehow, your headers can come after the checkboxes, you can use the CSS sibling selector to select it:

div {
  font-size: 30px;
  margin-bottom: 30px;
}

input:checked div {
  opacity: 0.5;
}
<label for="chk_one">Mark as done</label>
<input type="checkbox" id="chk_one" />
<div id="one">One</div>

<label for="chk_two">Mark as done</label>
<input type="checkbox" id="chk_two" />
<div id="two">Two</div>

<label for="chk_three">Mark as done</label>
<input type="checkbox" id="chk_three" />
<div id="three">Three</div>

Here is a complete, CSS-only solution that uses the above and a little CSS flexbox hack to reverse the display order of the header and checkbox, if you're fine with wrappers:

div.wrapper {
  display: flex;
  /*            
  • Related