Raduken Raduken - 7 months ago 29
Javascript Question

jquery toggle class not working when is in other div

hi guys I am doing a toggle effect in my page, but i got error when i move the button close for other part of the page. If the button is in a part of html works if are for example in other div the button does not work.can you guy figure out what is going on? also can u say if that my jquery is clean? or need to be improved?

html:

<a href="#menu-toggle" class="btn btn-sidebar-close" id="close">
<i class="fa fa-times" aria-hidden="true"></i>
</a>

<a href="#menu-toggle" id="menu-toggle"data-toggle="tooltip>
<i class="fa fa-search fa-2x" aria-hidden="true"></i>
</a>


js:

$('#close').click(function(e) {
e.preventDefault();
$('#wrapper').toggleClass('toggled');
});

$('#menu-toggle').click(function(e) {
e.preventDefault();
$('#wrapper').toggleClass('toggled');
});

Answer

An improvement could be:

$('#close').click(function(e) {
       e.preventDefault();
       $('#wrapper').toggleClass('toggled');
});

$('#menu-toggle').click(function(e) {
       e.preventDefault();
       $('#wrapper').toggleClass('toggled');
});

in a single function as they're both containing the same functionality:

$('#close, #menu-toggle').click(function(e) {
      e.preventDefault();
      $('#wrapper').toggleClass('toggled');
});
Comments