Custom JS script on your page and tricks with customization

Available in service plans: Advanced, Universal


If you would like to run some JS script on your page you can add it in your Project settings -> Custom CSS/JS -> External or Embedded (JS/CSS). Example:


<script>
alert('test');
</script>

Sometimes you need to run the script when page is ready. We have a special array of methods (initqueue) which we run when page is ready. Just add your method to this array.


<script>
initqueue.push(function(){
    // your code is here
});
</script>

You are able to use JQuery library when page is ready!


Additionally, sometimes you need to run a script when "topic popup" is ready. For example, to customize the topic form. We have a special event for this case: uetopicpopuploaded.


Here is an example how to add some text to the topic popup.


<script language="javascript">
initqueue.push(function(){
    $(window).on('uetopicpopuploaded', function () {
        $('#module_add_topic .modal-body').prepend('<div style="background-color: #ffdd99;padding:10px;margin-bottom:10px"><strong>Test message in the topic popup</div>');
    });
});
</script>

One more example: pre-defined text in the description field if field is empty.


<script language="javascript">
initqueue.push(function(){
    $(window).on('uetopicpopuploaded', function () {
        var description_field = $('#module_add_topic .redactor-editor:first');
        if ( description_field.length > 0 &&  description_field.html()=='<p></p>'){
              var text = "<p>;text line 1<br>text line 2</p>";
               description_field.html(text);
        };
    });
});
</script>


Show/Hide specific custom fields by selected category in the Topic form

<script language="javascript">
// show/hide fields by selected category
function onCategorySelected(){
  var selected_category = this.value;
  // custom field ids to show/hide by category id
  var cf_by_cat_settings = {'64':[13,17],'81':[10,11,12,13]};
  for (var key in cf_by_cat_settings) {
    for (i = 0; i < cf_by_cat_settings[key].length; i++) { 
      // check if show or hide
      var show = (key == selected_category) || (selected_category in cf_by_cat_settings && cf_by_cat_settings[selected_category].indexOf(cf_by_cat_settings[key][i]) != -1);
      // show or hide
      $('form#id_topic_form #id_cf_'+cf_by_cat_settings[key][i]).closest('.form-group').toggle(show);
    }
  }
};
// add script to queue
initqueue.push(function(){
  // execute script on topic form loaded 
  $(window).on('uetopicpopuploaded', function () {
    var category_selector = $('form#id_topic_form select#id_category');
    // call method by 'change' event
    category_selector.on('change', onCategorySelected);
   // call default selected 
   category_selector.change();
  });
});
</script>


This article was helpful for 7 people. Is this article helpful for you?