3

I have a hidden modal box on my page that gets rendered with the call of this create.js file.

Everything else is working nicely except for adding a data-meal_id attribute to the element.

Here's the jquery:

var $modal, $modal_close, $modal_container, $meal_id;
$modal = $('#modal');
$modal_close = $modal.find('.close');
$modal_container = $('#modal-container');
$meal_id = <%= @meal_id %>

$modal
  .data('meal_id', $meal_id)
  .prepend($modal_close)
  .css('top', $(window)
  .scrollTop() + 100)
  .show();

$modal_container.show();

$(document).on('click', '#modal .close', function() {
  $modal_container.hide();
  $modal.hide();
  return false;
});       

Here are the elements before the above code is triggered:

<div id="modal-container"></div>
<div id="modal">

After being triggered...

<div id="modal-container" style="display: block;"></div>
<div id="modal" style="top: 100px; display: block;"><a href="#" class="close">cancel</a>

Totally skips the data attribute??!

1 Answer 1

8

The .data() method does not modify the dom if you want to set a data attribute of an element you'll have to use attr()

$modal
  .attr('data-meal_id', $meal_id)
Sign up to request clarification or add additional context in comments.

1 Comment

jQuery has it's own internal data object that it uses, it doesn't use dataset DOM API, nor does it modify the markup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.