3
\$\begingroup\$

I am looking to simplify this code as it is to bulky for what it is doing. I do not need to stick to jQuery.

Simple checkbox in html relates to adding underline to some text:

$("#houseOrCar").on("change", function () {
    if ($(this).is(":checked") ) {
        $("#houseChosen").css("text-decoration", "none");
        $("#carChosen").css("text-decoration", "underline");
    } 
    else  {
        $("#houseChosen").css("text-decoration", "underline");
        $("#carChosen").css("text-decoration", "none");
    };
});
\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

You could use a class that would only hold the property for the active element, in our case text-decoration: underline;. Then simply toggle each of the two labels to set on and off this "active" class (here called underline). So you don't need to know which label is which, both will toggle anyway. Just set one of the two to have the class .underline on page load.

Plain JavaScript

const toggle = () => document.querySelectorAll('#labels > div')
  .forEach(label => label.classList.toggle('underline'))

document.querySelector('#houseOrCar').addEventListener('change', toggle);
.underline {
  text-decoration: underline;
}
<input type="checkbox" id="houseOrCar">

<div id="labels">
  <div class="underline">HOUSE</div>
  <div>CAR</div>
</div>

Note I'm using the .forEach method of the nodeList class:

The forEach() method of the NodeList interface calls the callback given in parameter once for each value pair in the list, in insertion order.


jQuery

And here it is implemented with jQuery, which is shorter but very similar:

const toggle = () => $('#labels > div')
  .each((i,e) => $(e).toggleClass('underline'));

$('#houseOrCar').on('change', toggle);
.underline {
  text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="houseOrCar">

<div id="labels">
  <div class="underline">HOUSE</div>
  <div>CAR</div>
</div>

It's not worth using jQuery for this, personally, I would stick with the plain version. However, if you happen to already use jQuery in your project then go for it!

\$\endgroup\$
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.