Jquery Press show hide button using if for css

I'm trying to make a button that toggles the visibility of another div ... here is the javascript that I use

$(document).ready(function () { var navwidth = $('div#navigationpanel').css('max-width'); $('div#showhidenav').click(function () { if ( navwidth == "0px" ) { $('div#navigationpanel').css('max-width', '850px'); } else if ( navwidth == "850px" ) { $('div#navigationpanel').css('max-width', '0px'); } }); }); 

And it really works, at the beginning of the first click, but the second time I press the button, it should do the opposite so that the ether again shows or hides the div. But nothing happens.

So, to be clear, it works for the first click, but not for the next

+4
source share
4 answers

This is because you are using the stored value (in DOMReady) and you are not updating it, therefore it is performed only from condition blocks, the css method accepts a function, you can use this function:

 $(document).ready(function () { $('#showhidenav').click(function () { $('#navigationpanel').css('max-width', function(i, m){ return m === '850px' ? '0px' : '850px'; }) }); }); 
+5
source

Use .on()

 $('div#showhidenav').on('click',function () { var navwidth = $('div#navigationpanel').css('max-width'); if ( navwidth == "0px" ) { $('div#navigationpanel').css('max-width', '850px'); } else if ( navwidth == "850px" ) { $('div#navigationpanel').css('max-width', '0px'); } }); 

put navwidth inside the click event call.

+2
source

You set the variable to load the page and do not refresh it when the div changes. To fix this, you can check the value instead of using a variable

 $(document).ready(function () { $('div#showhidenav').click(function () { if ( $('div#navigationpanel').css('max-width') == "0px" ) { $('div#navigationpanel').css('max-width', '850px'); } else if ( $('div#navigationpanel').css('max-width') == "850px" ) { $('div#navigationpanel').css('max-width', '0px'); } }); }); 

But if you just want to show and hide the div, then jQuery has a built-in .toggle() function

 $(document).ready(function () { $('#showhidenav').click(function () { $('#navigationpanel').toggle(); }); }); 

You can specify the duration and attenuation for the transition. From jQuery documentation

.toggle (duration [, easing] [, complete])

 duration (default: 400) Type: Number or String A string or number determining how long the animation will run. easing (default: swing) Type: String A string indicating which easing function to use for the transition. complete Type: Function() A function to call once the animation is complete. 
0
source
  • Do not use the tag#id selector, just #id , the first one makes it slower
  • Cache of your target
  • Use .on() to listen for events
  • Use .slideToggle()

CSS

 #navigationpanel { max-width: 850px; } 

Js

 $(document).ready(function () { var $nav = $('#navigationpanel'); $('#showhidenav').on('click', function () { $nav.slideToggle(); }); }); 
0
source

All Articles