[SOLVED] Adding JQuery to a PlayCanvas Project

Hi all!
I’m new and i hope оpе you can help me with a little problem with JQuery.

I need to execute some code on $(document).ready(). How can i do that? Where do I need to place the script? Because if I write it in Script Asset, the line is never executed.

Thanks!

All the JS scripts in PlayCanvas are placed in the <script> tags at the top of the HTML. So you can put this in and script asset but don’t put it in the initialise functions or anything like that.

Here is an example project: https://playcanvas.com/editor/scene/563633

Also, make sure that the jQuery library is loaded before the other scripts that use it in the script loading order in the project settings.

2 Likes

project : https://playcanvas.com/editor/scene/563633 is no longer available

Hi,

Sorry for necroing this post.
I’m currently trying to implement some jquery in a project and this question is pertinent.

Where do I put my script? The link is still no longer working.

You can either just add the script to the project as a .JS file or use External Scripts in the settings of the editor.

Thanks, adding the link in external scripts removed my error.

Now, lets say my html had this very simple script:

  $( function() {
    $( "#color_button" ).on( "click", function() {
      $( ".bouton_uncover" ).removeClass( "bouton_cover" );
	  $( ".submenu" ).addClass( "submenu_open", 1000 );
	  $( ".color_container" ).addClass( "visible");
	  $( ".finish_container" ).removeClass( "visible");
	  $(this).addClass( "bouton_cover", 0);
    });	
});

It just used to be in a html tag at the bottom of my html page, but once in playcanvas, it no longer works.

Any idea where this one needs to go?

Hi @PixiLabo,

Yeah it doesn’t work because your HTML is appended to the DOM at a later point, much later when the browser executes the base javascript.

To fix that you can easily run this javascript from any Playcanvas script just make sure you run it AFTER the html has been appended to the DOM:

jQuery( "#color_button" ).on( "click", function() {
  jQuery( ".bouton_uncover" ).removeClass( "bouton_cover" );
  jQuery( ".submenu" ).addClass( "submenu_open", 1000 );
  jQuery( ".color_container" ).addClass( "visible");
  jQuery( ".finish_container" ).removeClass( "visible");
  jQuery(this).addClass( "bouton_cover", 0);
});	
  • You need also to make sure that you have jQuery loaded to your Playcanvas project.
  • I’ve replaced the $ with jQuery, if you aren’t doing anonymous functions like in your example it would need the full reference to the jQuery global object.
2 Likes

Thank you very much! It works now.

1 Like