简体   繁体   中英

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');
});

You forgot to close quote after "tooltip" here :

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

Otherwise, your code is working :

See this Fiddle

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');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM