I'm just a bit confused and can not write or simplify a jQuery code, that adds or removes classes based on the viewport size. I'm pretty sure there's a simpler and more efficient way to write that trivial code. Unfortunately I can not get it.
Here is the current status:
// initial state
if ($(window).width() <= 900) {
$('.readmoresection span.handler').show();
$('.readmoresection').addClass('reduced');
}else{
$('.readmoresection span.handler').hide();
$('.readmoresection').removeClass('reduced');
}
// on resize
$(window).on('resize', function(){
if ($(window).width() <= 900) {
$('.readmoresection span.handler').show();
$('.readmoresection').addClass('reduced');
if($('.readmoresection').hasClass('reduced')){
$('.readmoresection span.handler').html(' » Weiterlesen');
}else{
$('.readmoresection span.handler').html(' » Schließen');
$('.readmoresection').removeClass('reduced');
}
}
else{
$('.readmoresection span.handler').hide();
$('.readmoresection').removeClass('reduced');
}
});
Does anyone know a cleaner way?
if($('.readmoresection').hasClass('reduced'))is always true since you add the calss right before you check the condition. this is probably not the desired behavior \$\endgroup\$