Quick Tip :: Media Queries for JQuery???
I know this is not a good term. Even very stupid!!! It is not really media queries. Just anif
- else
statement to make some function run or not based on window size.
Normally, we have to write some media queries such as these:
@media screen and (max-width:760px) {
#sidebar {display:none;}
}
But, how about JavaScript in media queries?? We can't control JavaScript with CSS! And also, we can't hide some script with CSS like this:
@media screen and (max-width:760px) {
script#work1 {display:none;}
}
For the alternative way, we can just use the if
- else
statement to do that.The Basic
First, we need to get the window width for a comparison:var winWidth = $(window).width(); // Get the window width
The If - Else Statement
Then, add a simpleif
- else
statement and focus on the window size for the condition:
if(winWidth < 870) {
// Any code here will run only when the screen width less than 870 pixels
} else {
// Reset the code here. So, when the screen is expanded, your basic function will run again.
}
For Example
Say that you want a sidebar appear when the screen width is greater than 1024 pixels, but when the screen width is less than 1024 pixels, hide the sidebar:function showSidebar() {
$('#sidebar').show();
}
showSidebar();
if(winWidth < 1024) {
$('#sidebar').hide();
} else {
showSidebar();
}
Advanced
You can also add some effect such like transitioning element with CSS transition and media queries. But here, we will use the JQuery effect:function showSidebar() {
$('#sidebar').slideDown('slow', "easeOutBounce");
}
if(winWidth < 1024) {
$('#sidebar').slideUp('slow', "easeInOutExpo");
} else {
showSidebar();
}
Or...
Or, multiple statement:function showSidebar() {
$('#sidebar').slideDown('slow', "easeOutBounce");
}
if(winWidth <= 1024) && (winWidth > 970)) {
$('#sidebar').slideUp('slow', "easeInOutExpo");
} else if(winWidth < 970) {
...
} else {
showSidebar();
}
Great Job sir,
ReplyDeletewait for next tutorial :)
haha it is not responsive style but hidden style kwkwkw nice sir
ReplyDeletewew kirain cuma satu posting taunya mesti baca ampe tujuh baru mudeng saya bang hehe
ReplyDeletewelleh2...
ReplyDeletebner3 ne yaah...
kren bgtt...! TOP...!
like this... cara buat nya gmn Om ??? :)
ReplyDeleteTKJ Comunity