I am just working on my first live jQuery project and I could use a little advice.
The project is displaying a table of products (cakes in this case) + an image and description of the current product. When the page loads the first product in the list is selected but when the user hovers over a different item in the product list the displayed details change.
The jQuery code below works but it isn't very elegant and I would like to improve it. The code to highlight the product is largely duplicated so I think it should be in a function (but I couldn't get that to work properly) and I had trouble selecting the first item in the table (hence the messy :first code in the first section).
- /*
- * jquery for bake_to_order.php page
- */
- $(document).ready(function() {
- /*
- * Highlight first product in table and display img + text
- */
- $('#product_table tbody > tr:first').ready(function(){
- $('#product_table tbody > tr:first').addClass('current_product_row')
- var productImage = 'images/' + $(this).find('.product_image_url:first').text()
- var productDescription = $(this).find('.product_description:first').text()
- $("#current_img").attr({
- src: productImage,
- alt: productDescription
- })
- $("#current_description").text(productDescription)
- }) ;
- /*
- * When user hovers over a different product highlight that and display associated img + text
- */
- $('#product_table tbody > tr').hover(function() {
- $('.current_product_row').removeClass('current_product_row');
- $(this).addClass('current_product_row');
- var productImage = 'images/' + $(this).find('.product_image_url').text();
- var productDescription = $(this).find('.product_description').text();
- $("#current_img").attr({
- src: productImage,
- alt: productDescription
- });
- $("#current_description").text(productDescription);
- });
- });
Can anyone offer a nicer way of doing this? I would like to be writing nice clean jQuery code rather than just code that sort of works.
Mark