\$\begingroup\$
\$\endgroup\$
3
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.
1 Answer 1
\$\begingroup\$
\$\endgroup\$
0
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 );
answered Sep 5, 2017 at 6:51
user148150user148150
default
id
attribute. I think however that the question itself is not really on-topic (cfr: help center) \$\endgroup\$