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');
}
\$\endgroup\$
  • \$\begingroup\$ function() { f() } can be just f that's as much as you can simplify I think. \$\endgroup\$ – elclanrs Feb 15 '18 at 19:47
  • 1
    \$\begingroup\$ @elclanrs can you explain? not sure I understand \$\endgroup\$ – noclist Feb 15 '18 at 19:51
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>

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ +1 for specifying $(StyleSelectedPlan).on \$\endgroup\$ – Muhammad Omer Aslam Feb 18 '18 at 13:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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