\$\begingroup\$
\$\endgroup\$
2
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
0
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
default
function() { f() }
can be justf
that's as much as you can simplify I think. \$\endgroup\$