Search code examples
javascriptjquerybootstrap-datetimepicker

How can I access $(this) element during a plugin configuration to get data() attributes with jQuery?


I am trying to configure the widgetpositioning for bootstrap-datetimepicker so that it opens based on whatever value I set in the data-vertical-position of the element.

For example, if I have the following html

<div class='input-group date' id='datetimepicker2' data-vertical-position="top">

I would want the menu to open on the top instead of "auto"

typically one would change where the widget open like so

$('.from').datetimepicker({
      widgetPositioning: {
          horizontal: 'auto',
          vertical: 'top'
      }
});

However, I want to access $(this) object during the configuration so can check to see if the element has data-vertical-position value that I should set. So I am trying to do it like this

$('.from').datetimepicker({
      widgetPositioning: {
          horizontal: $(this).data('horizontal-position') || 'auto',
          vertical: $(this).data('vertical-position') || 'auto'
      }
});

However, that is not working. $(this).data('horizontal-position') seems to be null all the time which set the position to the default auto.


Solution

  • If the plugin does not support this type of setup, you can do it manually instead

    $('.from').each(function() {
      var from = $(this);
    
      from.datetimepicker({
        widgetPositioning: {
          horizontal: from.data('horizontal-position') || 'auto',
          vertical: from.data('vertical-position') || 'auto'
        }
      })
    });