0
\$\begingroup\$

I'm looking for a better way of writing this repetitive jQuery function:

(function($) {
  var mobileAmount = 300;

  $('#_100').click(function() {
    $('*').removeClass('-amount-active');
    $('#_100').addClass('-amount-active');
    mobileAmount = 100;
  });
  $('#_200').click(function() {
    $('*').removeClass('-amount-active');
    $('#_200').addClass('-amount-active');
    mobileAmount = 200;
  });
  $('#_300').click(function() {
    $('*').removeClass('-amount-active');
    $('#_300').addClass('-amount-active');
    mobileAmount = 300;
  });

  ...

})( jQuery );

There is a number of amount buttons and each time one is clicked it receives the active class for styling and updates the mobileAmount variable.

\$\endgroup\$
  • \$\begingroup\$ Well the info is a bit succinct, however it seems that the amount is a decisive factor, so either loop the possible different amounts per 100 or find a shared selector and read the amount from the selectors id attribute. I think however that the question itself is not really on-topic (cfr: help center) \$\endgroup\$ – Icepickle Sep 4 '17 at 14:47
  • \$\begingroup\$ Please explain what you are trying to accomplish with this code, and make that the title of the question. (See How to Ask.) Ideally, you should include a demonstration (press Ctrl-M in the question editor). We could give you much better advice if you provide the full context. I suspect that code repetitiveness should not be your primary concern here — you probably have other issues like flexibility and correctness that you should worry about more. \$\endgroup\$ – 200_success Sep 4 '17 at 15:58
  • \$\begingroup\$ Thanks for your comments. Fortunately Sintu came up with just what I was after but I will keep this in mind when asking future questions. Is it still worth trying to improve the question or should I leave it now that it's been answered? \$\endgroup\$ – stevebasford Sep 5 '17 at 16:49
1
\$\begingroup\$

Steps to fix this:

  • Add class 'amount-button' to all buttons
  • Add attribute data-mobileamount to all buttons and assign values like 100, 200, .. to each button.

For example:
<button class="amount-button" data-mobileamount="100" >Mobile Amount 100</button >
<button class="amount-button" data-mobileamount="200">Mobile Amount 200</button>

 (function($) {
  var mobileAmount = 300;
  $('.amount-button').click(function() {
    $('*').removeClass('-amount-active');
    $(this).addClass('-amount-active');
    mobileAmount = $(this).data('mobileamount');
  });
})( jQuery );
\$\endgroup\$

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.