DevStud DevStud - 7 days ago 4
CSS Question

Jquery Show More, Show Less button have any other thinks

I am trying to make a show more, show less button using jquery and css.

My question is do you have any other good think about my code. I used if else statement if i can do it more good then if else statement then what should i do?

I just :



$("body").on("click", ".ShowMoreDetails", function(){
$(".container").toggleClass("active");
if ($(".ShowMoreDetails").text() == "Show more") {
$(".ShowMoreDetails").text("Show less");
}
else {
$(".ShowMoreDetails").text("Show more");
}
});

.container {
width:525px;
margin:0px auto;
background-color:red;
box-sizing:border-box;
border-radius:2px;
margin-top:50px;
overflow:hidden;
position:relative;
max-height:350px;
}
.footer-M {
width: 100%;
min-height: 100px;
position: absolute;
bottom: 0px;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(0, 0, 0, 0.65)), color-stop(100%, rgba(0, 0, 0, 0)));
background: -webkit-linear-gradient(bottom, rgba(0, 0, 0, 0.65) 0%, rgba(0, 0, 0, 0) 100%);
background: -o-linear-gradient(bottom, rgba(0, 0, 0, 0.65) 0%, rgba(0, 0, 0, 0) 100%);
background: -ms-linear-gradient(bottom, rgba(0, 0, 0, 0.65) 0%, rgba(0, 0, 0, 0) 100%);
background: -moz-linear-gradient(bottom, rgba(0, 0, 0, 0.65) 0%, rgba(0, 0, 0, 0) 100%);
background: linear-gradient(bottom top, rgba(0, 0, 0, 0.65) 0%, rgba(0, 0, 0, 0) 100%);
filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#a6000000', endColorstr='#00000000', GradientType=0);

}
.ShowMoreDetails {
z-index:999;
cursor:pointer;
float:left;
width:100%;
text-align:center;
color:#ffffff;
text-transform: uppercase;
-webkit-tap-highlight-color: transparent;
font-family: helvetica, arial, sans-serif;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
font-size:14px;
font-weight:600;
line-height:40px;
bottom:0px;
position:absolute;
}
.column1 {
width:100%;
height:300px;
background-color:blue;
margin-bottom:10px;
}
.active {
max-height:none !important;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="column1"></div>
<div class="column1"></div>
<div class="column1"></div>
<div class="column1"></div>
<div class="footer-M">
<div class="ShowMoreDetails">Show More</div>
</div>
</div>




Answer

You can use the ternary operator:

a = (condition ? b : c)

which is identical to

if (condition) { a = b; } else { a = c };

like so:

$(".ShowMoreDetails").text(
  $(".container").hasClass('active'‌​) ? "Show less" : "Show more"
); 

You should rather base the decision which text to show dependent on the viewstate, not on the triggering element's text.