Problems with passing data to Javascript from a Rails view via <%= content_tag %>

Viewed 37

I'm rather new to Rails and to programming in general, and I'm having issues passing data from a <%= content_tag %> in a Rails view to a Javascript function (in this case, specifically making use of fullcalendar). Inspecting the rendered page's HTML source shows the data properly ending up in the resulting div, but the data from it doesn't seem to make it into the Javascript function that's supposed to be referencing it.

The problem is probably something very basic since I have no previous experience with Javascript, but copious googling has not shown me any solutions.

The view contains the following content_tag:

<%= content_tag :div, "", class: "calendar_data", data: {start_date: '2021-10-12', end_date: '2021-10-19'} do %>
<% end %>

(Once this is working I'll replace those dates with variables.)

The relevant section of my application.js includes the following code:

function loadCalendar() {
  var calendarEl = document.getElementById('calendar');
  var calendar = new Calendar(calendarEl, {
    plugins: [timeGridPlugin],
    initialView: 'timeGrid',
    visibleRange: {
      start: $('.calendar_data').data('start_date'),
      end: $('.calendar_data').data('end_date')
    }
  });

  calendar.render();
};

Replacing the $('.calendar_data').data('start_date') and end_date bits with plain dates as strings (e.g. '2021-10-12') produces the expected behaviour, which is why it seems like what's going on is that those $. ... bits are failing to return the data they're supposed to be looking for. As far as I understand it, that data should be available, given that the rendered page's HTML contains a div with the expected content:

<div class="calendar_data" data-start-date="2021-10-12" data-end-date="2021-10-19">
</div>

(For completeness's sake, yes, I have installed jquery and application.js includes import $ from 'jquery'.)

What am I doing wrong here? What basic principle of this process have I failed to properly google for?

1 Answers

I've worked around this by making calendar_data an id rather than a class in the content_tag, and taking advantage of Javascript's getElementById and dataset functionality:

The resulting application.js code is this:

function loadCalendar() {
  var calendarEl = document.getElementById('calendar');
  var calendarData = document.getElementById('calendar_data');
  var calendar = new Calendar(calendarEl, {
    plugins: [timeGridPlugin],
    initialView: 'timeGrid',
    visibleRange: {
      start: calendarData.dataset.startDate,
      end: calendarData.dataset.endDate
    }
  });

  calendar.render();
};
Related