2

My problem is a bit more complicated than this, but essentially when the user changes something on the page I would like to mark that field as "dirty" in some way and use a confirm box to ensure the user actually wants to leave the page before losing changes.

I can't use a global "something changed" variable in this case because of the need to add/remove it on certain items based on other events that occurred.

The answer to the question in the subject should take multiple things into account:

  • General best practices - if such a thing exists for this stuff
  • Lookup speed - I've seen in many places that class names are faster
  • Browser compatibility - no super-fancy HTML5/CSS3 whizzbang features, please. I need this solution to work in IE7+, Firefox, Chrome, and Safari. Not too worried about versions on the non-IE browsers.

Basically, I have some jQuery code that looks like this:

$(":input").on("change", function(event) {
  // set something on $(this) to hold state for this item
  // $(this).addClass("my-dirty-flag");
  // or
  // this.setAttribute("data-dirty-flag", "data-dirty-flag");
});

Which option is "better" and why?

One thing that made me even consider asking this is that AngularJS seems to use properties on tags to do this sort of thing.

Andy
  • 8,749
  • 5
  • 34
  • 59
  • I would go for class to set the state – Arun P Johny Jan 27 '14 at 16:36
  • If you don't want to write your own you could take advantage of this plugin https://github.com/codedance/jquery.AreYouSure – xspydr Jan 27 '14 at 16:37
  • I pretty much have to write my own code for this. Thanks for trying! – Andy Jan 27 '14 at 16:38
  • Why not just set a variable? Look-up speed is not going to be noticeable is normal size forms. Premature optimization? – epascarello Jan 27 '14 at 16:39
  • Kinda looks like it, doesn't it? :P But no, this is for a large application and the code will be run on every page. – Andy Jan 27 '14 at 16:42
  • So it runs on every page. The bigger problem you have is sticking an onchange event on every single form element on the page. There are better solutions than that. Event Bubbling is what you want. The speed of a look-up for a class or attribute is milliseconds difference for large pages. That is not doing to be a performance bottleneck. There is no "right/best" way of doing it, it is personal opinion. – epascarello Jan 27 '14 at 16:44
  • Hmmm... So you mean to use something like `$(document).on('change', ':input', function(event) { ... stuff ... });` instead? – Andy Jan 27 '14 at 16:52

1 Answers1

1

I would use classes for that purpose, because you can look them up with native JS code. Looking for data-* attributes is a much heavier operation, since JavaScript will have to loop through all element attributes. You can check other posts to back me up, like the following:

jQuery select by class VS select by attribute

Community
  • 1
  • 1
Joao Almeida
  • 972
  • 2
  • 6
  • 19