Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with data in jQuery

I would like to ask for more an opinion than a question: What would the community recommend to do when you must do a webpage with lots of data, for example, a products listing, that should have some functionality like buy (adds to cart), sorting, etc. if you have to manipulate the data of the current product - price, title, image, link and other attributes? How you do it in your projects?

For example we have a page with dozens of products, each of them has attributes: price, title, description, image(URL), link(URL). How would you store the data to use it on some user interaction? Personally, I've done it by just inserting each of the attribute in tags, something like:

<div class="product" data-product_id="123">
  <div class="pr_title">Title</div>
  <div class="pr_body">Body</div>
  <div class="pr_img"><img src="http://www.www.www/img.png"></div>
  <div class="pr_link"><a href="http://www.stackoverflow.com/">Buy!</a></div>
</div>

This way I have my html structure for presentation and I worked with data in jQuery by something like:

var url = $('.product').find('.pr_link').find('a').attr('href');

But when the project got big and there were 10-15 more attributes added to each element, getting data from current product got pretty complicated and the code became mostly unreadable.

I thought of using same structure, but to keep data in some object like:

var products = {
    1: {
        title: "abc",
        description: "lorem ipsum",
        price: 25.19,
        img: "http://www.www.www/img.png",
        link: "http://www.stackoverflow.com"
    }
}

and keep markup as simple as possible, only using elements and styles needed for design with css:

<div class="product" data-product_id="123">
  <div class="title">Title</div>
  <div>Body</div>
  <img src="http://www.www.www/img.png">
  <a href="http://www.stackoverflow.com/">Buy!</a>
</div>

so onClick I would need to retrieve the id of the product and query it in our object "products":

var url = products[id].title;

While this is the most convenient way to work with it requires a new object.

Another idea was to keep all data in data- attributes of the parent div element like:

<div class="product" data-product_id="123" data-title="abc" data-body="Body">

but for much as I know jQuery doesn't work with data attributes well (natively).

So what are your suggestions? Maybe you have some even better ideas to share.

P.S. I tried to find some information on the subject, but most likely failed to find the way to formulate it well so I found nothing about it. If there are links or even similar questions on stack exchange sites, please feel free to post them. Thank you in advance!

like image 904
Sergey Telshevsky Avatar asked Jun 17 '12 21:06

Sergey Telshevsky


People also ask

What is use of data in jQuery?

The data() is an inbuilt method in jQuery which is used to attach data or get data for the selected elements. Syntax: $(selector). data(para1); Parameter : It accepts an optional parameter “para1” which specifies the name of the data to retrieve for the selected element.

What is jQuery data API?

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.

How add data target in jQuery?

$("button"). on("click", function(){ $($(this). attr("data-target")). modal("show"); });

How read data attribute in jQuery?

Alternatively, you can also use the jQuery data() method (jQuery version >= 1.4. 3), to get the data-attribute of an element using the syntax like $(element). data(key) . That means in the above example to get the data-id using data() method you can use the statement like $(this).


1 Answers

You can use HTML5 data attribute to store products data, as you have several properties of products to associate with each product block, you can JSON encode the object and assign to the top element, and then can access that on user interaction on that element or any child element.

var product = {
    title: "abc",
    description: "lorem ipsum",
    price: 25.19,
    img: "http://www.www.www/img.png",
    link: "http://www.stackoverflow.com"
};
$(selector).data('product',JSON.stringify(product));

then to retrieve the object you can do on any event's callback

$product = $.parseJSON($(elem).data('product'));

In fact both facebook and twitter used data attributes to store associated data with tweets and stories. For example here goes some html of a FB story

<li data-ft='{"qid":"5757245005920960301","mf_story_key":"7164261693049558180"}'
 id="stream_story_4fe5d7d51bc415443080257">

You can see facebook is storing JSON encoded data into the data-ft attribute.

Similarly an example of a Twitter tweet html

<div data-tweet-id="216534496567230464" data-item-id="216534496567230464" 
data-screen-name="onimitch" data-user-id="123682011" data-is-reply-to="">

So twitter is saving associated data for a tweet into different attributes like data-tweet-id, data-user-id.

So As they both handle's a lot amount of data, I think You can also use either of the method to save your data without any performance issue.

If you store data with individual keys then be aware of the automatic data conversion that .data() does as @nnnnnn has already mentioned in comment.

Demo With .data() : http://jsfiddle.net/joycse06/vcFYj/

Demo With .attr() : http://jsfiddle.net/joycse06/vcFYj/1/

like image 164
Prasenjit Kumar Nag Avatar answered Sep 25 '22 12:09

Prasenjit Kumar Nag