2

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?

3
  • 1
    Could you show us how you're importing the file? Commented Aug 17, 2018 at 23:56
  • 1
    <script src="js/external.js"></script> Commented Aug 17, 2018 at 23:59
  • The name of the file is external.js. It is situated in js folder. Commented Aug 18, 2018 at 0:00

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.