Adding Javascript or Jquery code in Yii2

Registering inline scripts
Inline scripts are useful for configuration, dynamically generated code and small snippets. The registerJs() method for adding these can be used as follows:

Using inline scripts (code should be inserted after your view code ends)

$script = <<< JS 
 $(document).ready(function() { 
   alert("Hello jquery Inline"); 
JS; $this->registerJs($script, View::POS_END);

The first argument is the actual JS code we want to insert into the page. It will be wrapped into a <script> tag. The second argument determines at which position the script should be inserted into the page. Possible values are:

View::POS_HEAD for head section.
View::POS_BEGIN for right after opening <body>.
View::POS_END for right before closing </body>.
View::POS_READY for executing code on the document ready event. This will automatically register jQuery and wrap the code into the appropriate jQuery code. This is the default position.
View::POS_LOAD for executing code on the document load event. Same as the above, this will also register jQuery automatically.

The last argument is a unique script ID that is used to identify the script code block and replace an existing one with the same ID instead of adding a new one. If you don’t provide it, the JS code itself will be used as the ID. It is used to avoid registration of the same code muliple times.


You may also like...