JQuery: Uncaught TypeError: $ (...). click is not a function

I don't know where exactly I am going wrong. I am trying to just hide a certain div when another is clicked. Here is my jQuery (placed at the very bottom of the .html file):

<script>
    $(document).ready(function() {
        $(".card__container--closed").click(function () {
            $(".hide__overlay").hide();
        });
    });
</script>

<div class="hide__overlay">
    <p class="card__subtitle overlay card-overlay">NEWS</p>
</div>
<div id="card" class="card">
    ...some SVG image thing here...
</div>

      

However, for some reason I am getting the following error:

Uncaught TypeError: $(...).click is not a function
    at HTMLDocument.<anonymous>

      

I am using jQuery 3.2.1

...

+3


source to share


2 answers


All your problems are due to the fact that you are using jQuery 3, and a lot of things have been removed from jQuery 2. Remember that major version numbers mean they are allowed to include changes. For more information on jQuery 3.0+, see the jQuery 3.0 Upgrade Guide .

First, you don't need to $(document).ready()

. This was simplified long ago:

$(function() {
    // your code
});

      

In newer versions of jQuery, label event methods such as click()

have been deprecated as they are redundant. In recent versions, they are completely removed.



Instead, you need to use .on()

to set all event listeners.

$(".card__container--closed").on('click', function() {
    // ...
});

      

UPDATE: You mentioned in the comments that you have the same TypeError

from the method .hide()

. This is because it was removed in jQuery 3 as it often didn't play nicely with people's stylesheets. You can use addClass()

, removeClass()

and instead toggleClass()

to add your own show / hide classes to the element. You will then create these classes in your stylesheet to have complete control over how show and hide is achieved.

Read the jQuery 3.0 upgrade guide again as all your problems are based on deprecated methods that jQuery 3 no longer has.

+4


source


use document

or some other selector parent

in front of dynamically created elements to trigger events on this



$(document).ready(function() {
  $(document).on('click',".card__container--closed",function () {
     $(document).find(".hide__overlay").css('display','none');
  });
});

      

+1


source







All Articles