Ricky Gani Ricky Gani - 5 months ago 40
jQuery Question

w3school include HTML, javascript not working

So, I recently used w3school include html, so that i dont have to copy-paste same div to all my pages.

First, i used it for header and footer, which uses some CSS styling, and it has no problem, works perfectly.

But then, i tried to use it again for my dropdown Navbar, which include some javascript, the HTML got included fine, but the javascript that i put doesnt work ! Nothing is wrong with the javascript, it works fine when I didn't use the include HTML. Here's the code



$('#leftDrop1').on('click', function() {
if ($('#sub1').css('display') == 'block') {

$('#sub1').hide()

} else {
$("#sub1").show()
}
})

$('#leftDrop2').on('click', function() {
if ($('#sub2').css('display') == 'block') {

$('#sub2').hide()

} else {
$("#sub2").show()
}
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<script src="http://www.w3schools.com/lib/w3data.js"></script>

<div w3-include-html="dropdown.html"></div>





and here's what inside the dropdown.html

<div class="col-lg-3">
<ul id="dropKiri">
<li id="leftDrop1"><a class="dropIcon"><i class="fa fa-caret-right" aria-hidden="true"></i></a>Category 1</li>
<div id="sub1"><ul>
<li>Sub 1</li>
<li>Sub 2</li>
<li>Sub 3</li>
</ul></div>

<li id="leftDrop2"><a class="dropIcon"></a><i class="fa fa-caret-right" aria-hidden="true"></i></a>Category 2</li>
<div id="sub2"><ul>
<li>Sub 1</li>
<li>Sub 2</li>
<li>Sub 3</li>
</ul></div>

<li style="list-style-type: none;">Category 3</li>
</ul>
</div>


I dont know how to put 2 html pages on snippet, i'm sorry if this is a bit confusing

Answer

You need to delegate your events beacouse w3school script uses ajax and adds new items to the dom

$('body').on('click','#leftDrop1',function() {
  if ($('#sub1').css('display') == 'block') {

    $('#sub1').hide()

  } else {
    $("#sub1").show()
  }
})

$('body').on('click','#leftDrop2',function() {
  if ($('#sub2').css('display') == 'block') {

    $('#sub2').hide()

  } else {
    $("#sub2").show()
  }
})
Comments