I’m working on a product web page. This product page has multiple attributes such as size and color. I’m working on building an image swap script (jQuery) that will swap the main image on the page based on events.
Easy enough and there’s a million tutorials how to do that.
Where this gets less trivial is the attributes. I want to be able to swap images based on the aforementioned attributes selected.
First, the page will display an image that has been set as “default” for a given product.
Second, if someone clicks “size: large”, it will show the image that’s set for size large.
Third, if someone clicks “color: red”, it will pull the “large : red” image and swap it for the main image.
Fourth, if someone now clicks “size : small”, it will fetch the “small : red” image file.
Fifth, if someone now clicks “color : blue”, it will fetch the “small : blue” image file.
You get the idea.
I have a database with the size:color table. The question is, what is the best way to get this data in the HTML page so I can load it into JavaScript?
I want to avoid an AJAX call because of the extra network overhead and the page load will have already accessed the database and gathered all the data, I don’t want to call the database again and have it do all that work a second time.
I could hide the data with CSS (display:none) in the liked elements, but I would be concerned with SEO. There’s a bit of data to hide. There’s thumbnail image URLs, standard size and large size. I certainly wouldn’t want to save it as JSON format like that and just display:none.
I thought maybe saving it in HTML comments and using the jQuery comments() plug-in. I have concerns of speed and feasibility.
Any thoughts on how people best store data in the HTML file to access with JavaScript to build some nice page experience effects?
—- EDIT —-
Having slept on this, I’m thinking that I’m over thinking this whole thing. This whole time I’m trying to figure out how can I add all this product image information into HTML so JavaScript could use it add effects, when all I think I need to do is just have my PHP spit out the image/attribute table as a JavaScript object so I can use it. Instead of trying to figure out some way to re-load it from HTML. Which is just over thinking the whole thing.
You can spit out the page with a JavaScript block that contains the data for the product in JSON format.
Alternately you can get clever with class names and put the data in there:
red_A12345would parse out to red image = “A12345.jpg”