1

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? – Renon Stewart Feb 22 '16 at 18:31
10

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. – Design by Adrian Nov 15 '16 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 ? – SURENDER SINGH May 28 '18 at 5:47
6

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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