skip to Main Content

I want to trigger the js function when the class subcat-tab is clicked, but it seems not to be working. I don’t have any error messages but nothing is happening.

I’m under a phtml file from Magento 2.

<a href="#subcat_<?= $subcatId ?>" class="subcat-tab" title="<?= $subcat['label'] ?>" data-categoryid="<?= $subcatId ?>">

<script type="text/javascript">
    define([
        'jquery'
    ], function ($) {
        console.log("ok");
        $('.subcat-tab').click(function (e) {
            console.log(e);
        }
    });
</script>

4

Answers


  1. Chosen as BEST ANSWER

    Using require instead of define fix it somehow but don't really know why.


  2. Try this

    replacing "$(‘.subcat-tab’).click(function (e) {" with "$(‘.subcat-tab’).on(‘click’,function(e){"

    <script type="text/javascript">
        define([
            'jquery'
        ], function ($) {
            console.log("ok");
            $('.subcat-tab').on('click',function(e){
                console.log(e);
            }
        });
    </script>
    
    Login or Signup to reply.
  3. Using require is the right approach when you initialize javascript in a template file.
    define is used for javascript files in your web/js folders.

    Login or Signup to reply.
  4. Use require in this case instead of define.

    <script type="text/javascript">
       require(
          [
            "jquery"
          ], function($) {
             console.log("ok");
             $('.subcat-tab').on('click',function(e){
                console.log(e);
             }
       });
    </script>
    

    Or use with define:

    1: create a new sample.js file:

    define(
          [
            "jquery"
          ], function($) {
               return {
                  sampleClick: function(x){
                     console.log("ok");
                     $('.subcat-tab').on('click',function(e){
                          console.log(e);
                     }
                  }
               }
       })
    

    2: calling in main file

    <script type="text/javascript">
        require(
           [
            "jquery",
            "sample"
           ], 
           function($, sample) {
               sample.sampleClick();
        });
    </script>
    

    More information

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search