0
\$\begingroup\$

I have the following javascript that calls a function on page load and on click of an element on my page. Is this the cleanest way to do this?

StyleSelectedPlan();
$(document).on('click', '.select-plan', function () {
 StyleSelectedPlan();
});
function StyleSelectedPlan() {
 $('.radio-wrapper').removeClass('selected');
 $('.select-plan:checked').closest('.radio-wrapper').addClass('selected');
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Feb 15, 2018 at 19:45
\$\endgroup\$
2
  • \$\begingroup\$ function() { f() } can be just f that's as much as you can simplify I think. \$\endgroup\$ Commented Feb 15, 2018 at 19:47
  • 1
    \$\begingroup\$ @elclanrs can you explain? not sure I understand \$\endgroup\$ Commented Feb 15, 2018 at 19:51

1 Answer 1

3
\$\begingroup\$

As @elclanrs says, function () { StyleSelectedPlan(); } is redundant — you can just write StyleSelectedPath.

Since you're using jQuery, you should use $(document).ready(handler), or better yet, $(handler), to call the handler function when the page loads.

$(StyleSelectedPlan).on('click', '.select-plan', StyleSelectedPlan);
function StyleSelectedPlan() {
 $('.radio-wrapper').removeClass('selected');
 $('.select-plan:checked').closest('.radio-wrapper').addClass('selected');
}
.radio-wrapper.selected { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
 <li class="radio-wrapper"><input name="name" type="radio" class="select-plan" id="one"><label for="one">one</label></li>
 <li class="radio-wrapper"><input name="name" type="radio" class="select-plan" id="two"><label for="two">two</label></li>
 <li class="radio-wrapper"><input name="name" type="radio" class="select-plan" id="three" checked><label for="three">three</label> (preselected)</li>
</ul>

answered Feb 15, 2018 at 22:22
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.