Here is my question How can i make a click button when do i click make array.sort(x-y) and then click again to make array.sort(y-x)
i'm already have the function but i'm confuse how to do it...
let me clarify my question: when do i click on button i make sort to array from bigger to smaller number and then i would like to press on the same button to make the array sort from smaller to bigger
here is my code:
$(".lower").click(() => {
colorsValueMenu("highest", "spot", "gainers", "losers", "lower")
highest = arrayCoinsD.sort(function (a, b) { return b.quote.USD.percent_change_24h - a.quote.USD.percent_change_24h })
createCoinDiv(arrayCoinsD, arrayCoinsI)
$(".lower").click(() => {
colorsValueMenu("lower", "spot", "gainers", "losers", "highest")
lower = arrayCoinsD.sort(function (a, b) { return a.quote.USD.percent_change_24h - b.quote.USD.percent_change_24h })
createCoinDiv(arrayCoinsD, arrayCoinsI)
})
})
it's work but just on the first & second time... i want to make it like toggleClass action for every single click
CodePudding user response:
You should make your code DRY (Don't Repeat Yourself)
You can create a flag
and change the operations as per the flag
as:
let flag = "high";
$(".lower").click(() => {
// Highest
colorsValueMenu(
flag === "high" ? "highest" : "lower",
"spot",
"gainers",
"losers",
"lower"
);
highest = arrayCoinsD.sort(function (a, b) {
return flag === "high"
? b.quote.USD.percent_change_24h - a.quote.USD.percent_change_24h
: a.quote.USD.percent_change_24h - b.quote.USD.percent_change_24h;
});
createCoinDiv(arrayCoinsD, arrayCoinsI);
flag = flag === "high" ? "low" : "high";
});
CodePudding user response:
What you're doing right now is creating an event listener on #lower. This will do the sort(a-b) like you ask, but inside that event listener you are creating another event listener, which isn't going to work. What you can do instead is create a flag like someone in the comments suggested. An example would be:
flag = false;
("#lower").click(() => {
flag = !flag;
if (flag) {
//do this thing;
} else {
//do this other thing;
}
}
This way, the behavior alternates whenever you click it. You can then use that to sort in different ways.
CodePudding user response:
You can use the toggle
method to do ascending and when you click again descending like this:
$(".lower").toggle(function(){
// Ascending code or function
}, function (){
// Descending code or function
})
Check the official reference here: https://api.jquery.com/toggle-event/