Jquery not working on external JS file

191
August 18, 2018, at 7:10 PM

I have a custom dropdown menu that works perfectly fine when I add the script on the main html file but when i link it from an external JS file, the function seems to act faulty. It is not showing output.

This is the Script

$('.tc-navigation > a').click(function() {   
    var element = $(this).parent('li');
    element.children('ul').toggleClass('toto');
    return false;
});
$(document).click(function() {
    $('.tc-navigation > li > ul').removeClass('toto');
}); 

Do Jquery functions like parent(), children(), siblings() stuff like that work on an external JS file? If not, is there a way to make them work?

Answer 1

Are you loading your JavaScript file before the DOM is rendered?

Try the defer attribute:

<script src="js/external.js" defer></script>

defer:

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

Answer 2

You need to load first jQuery, later your functions. With jQuery you can wait until the dom is loaded and rendered also.

parent(), children(), siblings() functions will work fine in an external file.

Rent Charter Buses Company
READ ALSO
Creating a seach feature with jQuery and Bootstrap 4 [on hold]

Creating a seach feature with jQuery and Bootstrap 4 [on hold]

I was hoping someone had a code snippet or possibly a link or source to a which will help you utilize the search feature in bootstrap 4s NavBarI'm learning jQuery but I'm not even sure where to begin for searching for a word in a page or a set of webpages...

146
JQuery reveal div on click and hover of text link - a more elegant solution?

JQuery reveal div on click and hover of text link - a more elegant solution?

I've created the following script to reveal a text box on right when a navigation link is clicked on the left

108
How do I make this infinite jquery animation end when the user is no longer hovering?

How do I make this infinite jquery animation end when the user is no longer hovering?

At the moment when you hover on any of the three items in my menu, there is a light blue dot that begins flashing redI want that animation to stop when the user is no longer hovering over FormsItem1, FormsItem2, or FormsItem3 divs

139
Add, and delete value in string when checkbox clicked

Add, and delete value in string when checkbox clicked

I have quite a large number of checkboxes that I need to get the value of when checkedI would like to save them in a text field with id numbers and divider of ':'

167