2

I was wondering if anyone could provide a simple jQuerying hello world example in Magento 2. I have read the documentation on requireJS and the Magento 2 documentation and I am still struggling.

This is what I have in my script tag in my PHTML file.

require([ 'jquery'], function($){


    $( "p" ).click(function() {
        alert("Test!");
    });

});
1
  • The script above should work, what exact issue are you having? Did you run bin/magento setup:upgrade? Feb 22, 2016 at 18:31

3 Answers 3

12

Using jQuery simple example:

 <script type="text/javascript">
    require([ 'jquery', 'jquery/ui'], function($){ $(document).ready(function($) {
   alert("test");
}); });</script>

for your case:

   <script type="text/javascript">
    require([ 'jquery', 'jquery/ui'], function($){ $( "#yourid" ).click(function() {
    alert("Test!");
}); });</script>
2
  • 2
    You don't need to require jquery/uj unless you need to use it. Nov 15, 2016 at 18:09
  • <script type="text/javascript"> require([ 'jquery', 'jquery/ui'], function($){ $( "#checkoutnext" ).click(function() { alert("Test!"); }); }); </script> Not Working In Checkout What to DO ? May 28, 2018 at 5:47
7

You can also use domready!± in the require statement. That will mean your code won't execute until the dom is ready, same as using document ready.

require([
    'jquery',
    'domReady!'// wait for dom ready
], function ($) {

    $( "p" ).click(function() {
        alert("Test!");
    });

});
0
0

create requirejs-config

app/design/frontend/Smartwave/porto_child/Mageplaza_LayeredNavigation/requirejs-config.js

var config = {
    map: {
        '*': {
            customjs: 'Mageplaza_LayeredNavigation/js/custom_layerd'
        }
    }};

add js file

app/design/frontend/Smartwave/porto_child/Mageplaza_LayeredNavigation/web/js/custom_layerd.js

require([
    'jquery'
], function ($) {
    'use strict';
    //start the logic like
    $('.plus').parent().hasClass("opened");
    
});

use in phtml file app/design/frontend/Smartwave/porto_child/Mageplaza_LayeredNavigation/templates/layer/category_filter.phtml

<script type="text/x-magento-init">
{
    "*": {
        "Mageplaza_LayeredNavigation/js/custom_layerd": {}
    }
}
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.