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
Using
require
instead ofdefine
fix it somehow but don't really know why.Try this
replacing "$(‘.subcat-tab’).click(function (e) {" with "$(‘.subcat-tab’).on(‘click’,function(e){"
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.Use require in this case instead of define.
Or use with define:
1: create a new sample.js file:
2: calling in main file
More information