Home > Software design >  How to use JQuery Plugin in another js file
How to use JQuery Plugin in another js file

Time:11-13

I'm a beginner at JavaScript/jQuery, and I am stuck trying to get this to work. I'm trying to use jQuery mailcheck plugin.

I attached the script to HTML file at the end of the code.

<script src="/js/mailcheck.js"></script> // here is a plugin
<script src="/js/jquery-3.6.1.js"></script>
<script src="/js/script.js" defer></script> // here is my main script
<script src="/js/form.js" defer></script> // here is my below script 

This is my HTML

<nav >
    <label for="email">e-mail
        <input id="email" name="email" type="text" placeholder="[email protected]" required>
    </label>                       
    <div id="suggestion"></div>
</nav>

And this is what my script looks like. (form.js)

$('#email').on('blur', function() {
  $(this).mailcheck({
    domains: domains,                       
    secondLevelDomains: secondLevelDomains, 
    topLevelDomains: topLevelDomains,        
    suggested: function(element, suggestion) {
      // callback code
      $('#suggestion').html('Did you mean? '   suggestion.full)
      // console.log(suggestion)
    },
    empty: function(element) {
      $('#suggestion').html('')
    }
  });
});

And i got error

form.js:59 Uncaught TypeError: $(...).mailcheck is not a function
    at HTMLInputElement.<anonymous> (form.js:59:11)
    at HTMLInputElement.dispatch (jquery-3.6.0.js:5430:27)
    at elemData.handle (jquery-3.6.0.js:5234:28)

What am I doing wrong?

(I have to use JQuery)

CodePudding user response:

The <script> tag for the plugin needs to come after the <script> tag for jQuery. Like this:

var domains = ['gmail.com', 'aol.com'];
var secondLevelDomains = ['hotmail']
var topLevelDomains = ["com", "net", "org"];

$('#email').on('blur', function() {
  $(this).mailcheck({
    domains: domains,                       
    secondLevelDomains: secondLevelDomains, 
    topLevelDomains: topLevelDomains,        
    suggested: function(element, suggestion) {
      // callback code
      $('#suggestion').html('Did you mean? '   suggestion.full)
      // console.log(suggestion)
    },
    empty: function(element) {
      $('#suggestion').html('')
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/[email protected]/src/mailcheck.min.js"></script>

<nav >
    <label for="email">e-mail
        <input id="email" name="email" type="text" placeholder="[email protected]" required>
    </label>                       
    <div id="suggestion"></div>
</nav>

  • Related