I have a javascript function that changes a user preference, if they want weights to be metric or in imperial.
On my page I print out the weight, IE:
This is some description:
This product weights <b>200 KG</b>
Blah blah
I need to make it so that Javascript changes the weight measurement for all weights on the page, and am not sure the best way to tackle this. Can you create your own tags, or tag properties?
Thanks for any suggestions, JQuery is fine.
I’d recommend using
strongrather thanb, but the below will work for either of them.Edit: Better solution than using a class, with working example, below.
Tag the weights with a class, e.g.:Then in your JavaScript, you can switch like so:
Obviously you can condense that a bit, kept it verbose for clarity.
Better solution:
Tag the elements with the original weight (the one you store in your database) as a
data-weightattribute, e.g.:Then convert from that value:
Working example: http://jsbin.com/icure3
Attributes in the form
data-xyzwill pass validation as of HTML5; prior to HTML5 they are technically invalid, but harmless. But if you prefer a version that doesn’t usedata-weight, you can do it with classes instead: http://jsbin.com/icure3/2 (inspired by Reigel’s answer to Tom’s other question).If you see a delay when switching between metric and imperial on slower browsers (I’m looking at you, Microsoft), you can help jQuery’s selector engine optimize by giving it more context than just “[data-weight]”. jQuery’s engine supports nearly all of CSS3. For instance, if you always use the
data-weightattribute only one one kind of tag (say,strongtags), change the selector to “strong[data-weight]” so the selector engine knows it can optimize for just one specific tag name. Similarly, if all of these are inside some container (e.g., a div with the ID “productList” for instance), you can help the engine out even more (“#productList strong[data-weight]”) so it can ignore anything outside that div. I’ve kept it completely general above. But probably only bother if the page is big and complex enough that you see a performance issue.Final thought: To throw a bone to browsers with JavaScript disabled, you might include both values in a
titleattribute as well, e.g.:…so it shows up as a tooltip on browsers that do that. I included that in the example above.