Reputation: 55
I have question because I'm try hide menu when window width is more than 766px. This is my code but not work
HTML
<div class="menu">
<div class="burger-menu">
<span></span>
<span></span>
<span></span>
</div>
<ul class="submenu">
<li><a href="#about-me">O mnie</a></li>
<li><a href="">Prace</a></li>
<li><a href="">Certyfikty</a></li>
<li><a href="">Cennik</a></li>
<li><a href="">Kontakt</a></li>
</ul>
</div>
JQuery
//Burger menu
$('.burger-menu').click(function(){
$(this).toggleClass('open');
});
//Menu list
$('.burger-menu').click(function(){
$('.submenu').slideToggle();
});
if($(window).width() > 766){
$('.submenu').hide();
}else {
console.log('halo');
};
Everything works but when I click burger and menu slide for example on 677px and then resize window to more than 766px menu still there. Thanks for every help
Upvotes: 0
Views: 2574
Reputation: 1350
You could use CSS media queries, but since you want jQuery... On window resize, you need to check the width of the window. With your code, it's only running once.
$('.burger-menu').click(function(){
$(this).toggleClass('open');
});
//Menu list
$('.burger-menu').click(function(){
$('.submenu').slideToggle();
});
$(window).resize(function(){
if($(window).width() > 766){
$('.submenu').hide();
}else {
console.log('halo');
};
}
Upvotes: 2
Reputation: 72299
Problem:-
Window width checking code not running every-time when you are resizing your window.
Solution:-
Use jQuery resize() like below:-
$(window).resize(function(){
if($(window).width() > 766){
$('.submenu').hide();
}else{
console.log('halo');
//add $('.submenu').show(); to show menu
}
});
Note:- rest of the code is Ok.
Upvotes: 1
Reputation: 10975
To achieve expected result, use below CSS
@media (min-width: 766px) {
.submenu {
display: none;
}
}
Codepen - https://codepen.io/nagasai/pen/yXRVOe
Other option Using Jquery, make below changes to work on resize and on page load
On window resize, show the .submenu if the screen width is less than 766px and hide , if more than 766px
Use Jquery, follow below steps
if($(window).width() > 766){ $('.submenu').hide(); }
$(window).resize(function(){ if($(window).width() > 766){ $('.submenu').hide(); } else { $('.submenu').show();// add else condition to show if condition faile console.log('halo'); }; });
https://codepen.io/nagasai/pen/vZVyyz
Upvotes: 1
Reputation: 403
you should call the resize function in jquery //the function to hide the div function hideDiv(){
if ($(window).width() < 1024) {
$("#floatdiv").fadeOut("slow");
}else{
$("#floatdiv").fadeIn("slow");
}
}
//run on document load and on window resize
$(document).ready(function () {
//on load
hideDiv();
//on resize
$(window).resize(function(){
hideDiv();
});
});
or you can do it with css media query :
/* always assume on smaller screen first */
#floatdiv {
display:none;
}
/* if screen size gets wider than 1024 */
@media screen and (min-width:1024px){
#floatdiv {
display:block;
}
}
Upvotes: 0