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.

  • 1
    Setting just the data value using data api doesnt create a data-* attribute for the dom element, use ``.attr` instead. – PSL Oct 21 '13 at 17:57
  • Why are you using `data-*` attributes in the first place? – Benjamin Gruenbaum Oct 21 '13 at 17:58
  • @Ben: is there a reason not to? – David Thomas Oct 21 '13 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). – Benjamin Gruenbaum Oct 21 '13 at 18:01
  • I have other events that need the x-y positions –  Oct 21 '13 at 18:02
  • @IvanRistic This sounds like bad architecture to me. Have a backing model for what the x and y positions _represent_ , share knowledge between application parts _explicitly_ and make the dependencies of each part of your application obvious. – Benjamin Gruenbaum Oct 21 '13 at 18:12
  • Ever heard of variables? I hear they're pretty handy for this sort of thing. – Shmiddty Oct 21 '13 at 18:13

1 Answers1

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);
Jason P
  • 26,984
  • 3
  • 31
  • 45