I have two DIVs, one is used as button and appear on mobile screens only, and the other one contains information that I want always be visible on desktop and could be toggle on mobile using Show/hide button.
On mobile the information should be hidden initially. The issue is when I hide information on screen below 480px, it is not visible on screen above 480px
Hide the information by clicking Show/hide button then expend the screen you will find noting on screen, I want information be visible in this case.
Here is my code
$(document).ready(function() {
$('.show-hide').click(function() {
$(this).next().toggle();
});
});
.show-hide {
background-color: #ffa2a2;
padding: 8px;
display: none;
}
.information {
background-color: #a4dca4;
padding: 8px;
}
@media only screen and (max-width: 480px) {
.show-hide {
display: inline-block;
}
.information {
display: none;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="show-hide">Show/Hide Info</div>
<div class="information">
Some information here, Some information here, Some information here, Some information here, Some information here, Some information here, Some information here,
</div>
Hide the information by clicking Show/hide button then expend the screen you will find noting on screen, I want information be visible in this case
This behaviour is because the toggle()
call has added a style
attribute directly to the element which is difficult to override with CSS, which it needs to be when the media query state changes.
To fix this, use toggleClass()
instead. You can then ignore this class outside of the media query so the element is always shown.
$(document).ready(function() {
$('.show-hide').click(function() {
$(this).next().toggleClass('toggle');
});
});
.show-hide {
background-color: #ffa2a2;
padding: 8px;
display: none;
}
.information {
background-color: #a4dca4;
padding: 8px;
}
@media only screen and (max-width: 480px) {
.show-hide {
display: inline-block;
}
.information {
display: none;
}
.information.toggle {
display: block;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="show-hide">Show/Hide Info</div>
<div class="information">
Some information here, Some information here, Some information here, Some information here, Some information here, Some information here, Some information here,
</div>
You can use this example fiddle to see the effect working as you resize the window.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With