This code works fine, but it looks like it could be optimized as it just reverses the ternary order. Any idea how to achieve that?
if ($("#advanced-search-panel").hasClass("hidden")) {
adv_text.text(adv_text.text() == "Show advanced search" ? "Hide advanced search" : "Show advanced search");
}else{
adv_text.text(adv_text.text() == "Hide advanced search" ? "Show advanced search" : "Hide advanced search");
}
CodePudding user response:
Since adv_text.text()
only has two possibilities - show and hide - the entire condition
if ($("#advanced-search-painel").hasClass("hidden")) {
is superfluous, because no matter whether the class exists or not, you want to toggle the text from show to hide, or from hide to show, depending on what the text currently is. Your code simplifies to
adv_text.text(
adv_text.text() == "Show advanced search" ? "Hide advanced search" : "Show advanced search"
);
Another option would be to have an inline element for the part of the text that changes, so that you only have to check and change that.
<div><span >Show</span> advanced search</div>
const span = $('.adv-search-toggle-text');
span.text(span.text() === 'Show' ? 'Hide' : 'Show');
It sounds like the hidden
class might have something to do with the text toggling above. If it does, there's a chance you could use CSS rules alone to have Show
shown when the hidden class is applied, and Hide
shown when the hidden class isn't applied.
CodePudding user response:
As a first step: you want to have "Show advanced search"
as a result exactly if both $("#advanced-search-painel").hasClass("hidden")
and adv_text.text() == "Show advanced search"
are true or both are false, so you could have:
adv_text.text(
$("#advanced-search-painel").hasClass("hidden") == (adv_text.text() == "Show advanced search")
? "Hide advanced search"
: "Show advanced search"
);
But as @CertainPerformance points out, with the constraint of adv_text.text()
having only those two possible values, the if
and else
branch are achieving exactly the same, so there is no need for the if
actually.