0

I've created a navigation bar in my webpage that links to different html files using href. The navbar.html has javascript to change the active link UI to show the user which item is clicked that I load like this.

navbar.html

<script>
   require('../assets/navbar.js');
</script>

navbar.js

$('#sidebar-button').click(function() {
    $('.ui.sidebar').sidebar('toggle');
 });

 $('div.sidebar-items > a').click(function() {
    $(this).attr('class', 'active item');
    $(this).siblings().attr('class', 'item');

    $(this).find('i').addClass('teal');
    $(this).siblings().find('i').removeClass('teal');

    $('.ui.sidebar').sidebar('toggle');
 });

It will successfully load another html page and I include the same navbar.html in my search.html with:

search.html

<script> $(function() {
         $('#navbar').load("../html_pages/navbar.html", function() {
               $.getScript("../assets/navbar.js")
           });
      });
</script>

However, the active link does not change to the respective page that is clicked (in this case search.html). The navbar just loads as the original html was written. How can I make the navbar.js also execute and change the html when another page is loaded?

Tejas V
  • 28
  • 5
  • `require()` is part of Node.js: https://stackoverflow.com/a/9901097/378779. Are you writing this in Node? – kmoser Apr 01 '20 at 21:17

1 Answers1

0

Unless it's also a Jquery function, require() is a Node JavaScript function. You should be getting an error something along the lines of "require is not a function," or "require is not defined."

I believe your HTML
<script> require('../assets/navbar.js'); </script>

Should be
<script src='../assets/navbar.js'></script>

This will load the JavaScript from the source src file into the HTML page that the script is put into, although that is a relative tag so it may need to be modified to be relative to whatever page you're applying it to.

  • Thanks for the reply, but this still didn't work. I think the issue is when I load the navbar.html each time into my html files, it is resetting to the original html and in effect, overriding whatever javascript changes I've made. I need those changes to persist however. – Tejas V Apr 02 '20 at 02:27
  • Well, I actually don't know JQuery, so I can't find what's wrong with the code. –  Apr 02 '20 at 23:05