skip to Main Content

could you please help me find the problem in the below code?

When I open it in codepen it works. When I add it to my website, the JS is not working "$ is not defined". I’m a beginner so I don’t know how to define $.

HTML is:

<div id="contact">Contact</div>

<div id="contactForm">

  <h1>Keep in touch!</h1>
  <small>I'll get back to you as quickly as possible</small>
  
  <form action="#">
    <input placeholder="Name" type="text" required />
    <input placeholder="Email" type="email" required />
    <input placeholder="Subject" type="text" required />
    <textarea placeholder="Comment"></textarea>
    <input class="formBtn" type="submit" />
    <input class="formBtn" type="reset" />
  </form>
</div>

`$(function() {

$('#contact').click(function() {
  $('#contactForm').fadeToggle();
})
$(document).mouseup(function (e) {
  var container = $("#contactForm");

  if (!container.is(e.target) 
      && container.has(e.target).length === 0) // ... nor a descendant of the container
  {
      container.fadeOut();
  }
});

});`

2

Answers


  1. You must include the jQuery library in your HTML file before any custom JavaScript code that makes use of jQuery in order to resolve this problem. You can do this by including the following line of code in your HTML file’s head> section:

    *
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    *

    This will enable you to use the $ sign in your JavaScript code and load the jQuery library through a CDN (Content Delivery Network).

    Login or Signup to reply.
  2. I think you are using Jquery without linking its CDN, adding this in your HTML head section should solve this.

    <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search