Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  185] [ 6]  / answers: 1 / hits: 18373  / 8 Years ago, sat, november 12, 2016, 12:00:00

I'm trying to make it so that only when the browser is less than 768px, my navigation bar items will toggle hidden or shown when an element with navlogo is clicked. I know I'm not the most descriptive, but here's my code.



if ($(window).width() < 768) {

$(.navlogo).click( function (){
$(.navwrapper).toggle();
});
$(.navitem).click( function (){
$(.navwrapper).hide();
});

}


I know this is actually going to get marked as a duplicate but it's not. The thing is that I want it to be able to even work without refreshing. If it requires Angular.js then it would be helpful to know what code to use for that because I wouldn't mind using it but yeah I just want for the user to not have to refresh every time to get the correct result.



Also, one bug that happens when I don't have the



if ($(window).width() < 768) {}


is that yes it still works properly but even if the website is not in mobile mode, which occurs when the max width is 768px or lower, when the user clicks the element with navlogo, it still hides the navwrapper. That's not bad but the thing is that I also want it to hide when a user clicks on an element with navitem.



Thank you!


More From » jquery

 Answers
49

The if statement should be inside the click function:



$(.navlogo).click( function (){
if ($(window).width() < 768) {
$(.navwrapper).toggle();
}
});
$(.navitem).click( function (){
if ($(window).width() < 768) {
$(.navwrapper).hide();
}
});


Edit:



To hide/show the .navwrapper when the window is resized you can listen to the window resize event.



$(window).on('resize', function(e) {

if ($(window).width() > 767 && $(.navwrapper).is(':hidden')) {
$(.navwrapper).show();
}

});


Some considerations:




  • Try to use variables for selectors that will be called several times

  • For efficiency try to enclose what happens in the resize function in a timeout

  • Try to use CSS where possible for responsive instead of JavaScript


[#60081] Thursday, November 10, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
magdalena

Total Points: 364
Total Questions: 101
Total Answers: 92

Location: Namibia
Member since Mon, Nov 14, 2022
2 Years ago
;