0

This should save the x/y position of a canvas click to the canvas element as data attributes, but for some reason, they do not appear in the HTML when i inspect it with Chrome.

$('#canvas').click(function(e){
    $(this).data("pos-x", e.offsetX);
    $(this).data("pos-y", e.offsetY);
});

If i add a console log prior to this.data, the values are there, are they are not empty, what seems to be the issue?

It seems very straight forward, so i have a hard time seeing the problem.

7
  • 1
    Setting just the data value using data api doesnt create a data-* attribute for the dom element, use ``.attr` instead. Commented Oct 21, 2013 at 17:57
  • Why are you using data-* attributes in the first place? Commented Oct 21, 2013 at 17:58
  • @Ben: is there a reason not to? Commented Oct 21, 2013 at 17:59
  • 1
    @DavidThomas Yes. In 99.9% of cases they violate separation of concerns. They're used to mix application presentation logic with business logic. Usually, at least from my anecdotal experience they stem either from lack of knowledge of other data structures or from not knowing about separation of concerns (and having a backing data model being the single source of truth for your presentation). Commented Oct 21, 2013 at 18:01
  • I have other events that need the x-y positions Commented Oct 21, 2013 at 18:02

1 Answer 1

3

jQuery reads from data- attributes, but data('key', value) doesn't modify element attributes. jQuery uses its own internal data store. If you actually want to add/change the data- attributes, use attr():

$(this).attr("data-pos-x", e.offsetX);
$(this).attr("data-pos-y", e.offsetY);
Sign up to request clarification or add additional context in comments.

Comments