0

I've been looking for an answer for quite a long time now, But I couldn't find it. All of the answered questions on here did not work for me. I'm making an admin panel which has a sidebar. I want to make a button where if u click on it, the sidebar collapses. This is my code:

HTML

<li class="nav-item mr-3 sidebar-toggle">
 <button class="sidebar-toggler btn btn-sidebar-toggle" type="button" id="sidebar-toggler">
    <i class="fal fa-bars"></i>
 </button>
</li>

I inserted my jQuery file by doing this:

<script type="text/javascript" src="js/jquery-3.3.1.min.js" ></script>

At the bottom of my page. The path to the file is perfectly fine.

jQuery code

$(document).ready(function () {

    $('#sidebar-toggler').on('click', function() {
        $('#sidebar').toggleClass('active');
        $('#navbar-brand').toggleClass('active');
    });

});

The weird thing is. If I open up the console with F12 and paste the jQuery code in there, It works perfectly fine. What am I doing wrong?

PS: The classes active do exist. I've tested it in the console (See message above)

Rainier laan
  • 837
  • 1
  • 19
  • 44

2 Answers2

1

It sounds like the element doesn't exist on page load and is added asynchronously using javascript

Try delegating the event

$(document).ready(function () {

    $(document).on('click','#sidebar-toggler', function() {
        $('#sidebar').toggleClass('active');
        $('#navbar-brand').toggleClass('active');
    });

});

See: Understanding Event Delegation

charlietfl
  • 164,229
  • 13
  • 110
  • 143
1

Make sure your JavaScript code is after the jQuery reference. The code that you posted works fine. Perhaps there is an issue somewhere else, so consider posting the rest of your code if you need more help. Here is a demo of your code working, I hope it helps you finding the issue in your code:

$(document).ready(function() {
  $('#sidebar-toggler').on('click', function() {
    $('#sidebar').toggleClass('active');
    $('#navbar-brand').toggleClass('active');
  });

});
#sidebar {
  background-color: blue;
}

#navbar-brand {
  background-color: green;
}

#sidebar.active {
  background-color: red;
}

#navbar-brand.active {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="nav-item mr-3 sidebar-toggle">
  <button class="sidebar-toggler btn btn-sidebar-toggle" type="button" id="sidebar-toggler">
    <i class="fal fa-bars">test</i>
 </button>
</li>

<div id="sidebar">
  sidebar
  <div id="navbar-brand">brand</div>
  sidebar
</div>
Racil Hilan
  • 22,887
  • 12
  • 43
  • 49