Home › Forums › JavaScript › Replace image without page reload??
- This topic is empty.
-
AuthorPosts
-
January 7, 2012 at 12:08 pm #36007BlackhawksoMember
Hey everyone
I’m guessing that what I want to do will use either javascript or jquery, I am building an online catalogue for a company. Some of the products that they sell have different variations (i.e. colour, shape, size etc etc) now in the page that presents the item to the visitor I am showing an image of the item. What I would like to do is have a series of drop down menu’s that have the different versions of the product listed and when someone selects let say a different colour I would like the image to change to a different one showing the colour that they have selected but without a full page refresh. How could I go about doing this baring in mind that at the maximum their could be 3 or 4 drop down menu’s effecting the image displayed. If it affects it at all, all the details of the products including the filenames of the images are stored in a mySQL database.
Thank you for your time people.
Phil
August 9, 2016 at 10:40 am #244342liveFor10Participantthank you @cnwtx. You show how to change the image if the image is defined in the DOM hierarchy. How would you change the image if the image was defined in CSS?
Thanks,
DonAugust 10, 2016 at 1:57 am #244349giudevParticipantThis could be just a simplified way to resolve the thing.
It’s just a simplified front end code with jQuery, but of course there are dozen of ways to achieve the same result.Attach the different images to a data attribute.
HTML
<img src="main-image.jpg" id="123ABC"> <div class="dropdown"> <a id="your-dropdown-activator" href="#">CLICK ME TO OPEN THE DROPDOWN MENU</a> <ul class="dropdown-menu"> <li data-image="image-variation01.jpg" data-product-linked="#123ABC">Item variation #01</li> <li data-image="image-variation02.jpg" data-product-linked="#123ABC">Item variation #02</li> <li data-image="image-variation03.jpg" data-product-linked="#123ABC">Item variation #03</li> <li data-image="image-variation04.jpg" data-product-linked="#123ABC">Item variation #04</li> </ul> </div>
jQuery
$('.dropdown-menu > li').click(function(){ let img_element_selector = $(this).data('product-linked'); let img_new = $(this).data('image'); let img_element = $(img_element_selector); img_element.attr('src',img_new); })
You could also create a json object containing all the images (this could come from your back end code) and use javascript to cycle through it or create an Ajax function to get from the database the right image on click.
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.