Javascript issue in Rails View

In my Rails View template, I use some jQuery tab functions:

<section>
... content ommitted
</section>
<script>
$(document).ready(function () {
  $('.accordion-tabs-minimal').each(function(index) {
     $(this).children('li').first().children('a').addClass('is-active').next().addClass('is-open').show();
  });

  $('.accordion-tabs-minimal').on('click', 'li > a', function(event) {
     if (!$(this).hasClass('is-active')) {
      event.preventDefault();
      var accordionTabs = $(this).closest('.accordion-tabs-minimal')
      accordionTabs.find('.is-open').removeClass('is-open').hide();

      $(this).next().toggleClass('is-open').toggle();
      accordionTabs.find('.is-active').removeClass('is-active');
      $(this).addClass('is-active');
     } else {
      event.preventDefault();
    }
  });
});
</script>

Since I also use this script in other View templates, and I want to improve my Javascript a bit, I created a Javascript file (tabbed_panels.js) in app / assets / javascripts and moved the above script to the tabbed_panels.js file.

However, now the panels on my page have no content the first time the page loads. Only when the page is refreshed do the panels load with content.

Does anyone have an idea what is happening and how to solve it, so my dashboards have content when loading the first page?

thank you for your help,

Anthony

0
source share
1

Turbolinks

, $(document).ready Turbolinks.

( Turbolinks), Turbolinks <body> , , , JS DOM, JS

- JS Turbolinks ( Turbolinks):

#app/assets/javascripts/tabbed_panels.js
var new_items = function() {
  $('.accordion-tabs-minimal').each(function(index) {
     $(this).children('li').first().children('a').addClass('is-active').next().addClass('is-open').show();
  });

  $(document).on('click', '.accordion-tabs-minimal li > a', function(event) {
     if (!$(this).hasClass('is-active')) {
      event.preventDefault();
      var accordionTabs = $(this).closest('.accordion-tabs-minimal')
      accordionTabs.find('.is-open').removeClass('is-open').hide();

      $(this).next().toggleClass('is-open').toggle();
      accordionTabs.find('.is-active').removeClass('is-active');
      $(this).addClass('is-active');
     } else {
      event.preventDefault();
    }
  });
});

$(document).on("page:load ready", new_items);

, , Turbolinks .

-

JS

- , ( ), , javascript .

Unobtrusive JS , "" Javascript . :

  • JS ( DRY)
  • JS "" ( )
  • JS /, .

JS , ,

+1

Source: https://habr.com/ru/post/1665271/


All Articles