Jump to content

Change Image using jQuery


Recommended Posts

I have never done any jQuery programming before, and I am having a hell of a time finding a tutorial to do what I would like.  Maybe I am looking for the wrong thing?


I have this scenario:


I have a product that has two or more images.  I have one div where the product image is displayed.  What I would like to do is have a 'next' and 'previous' button that cycles through the product images.  I would love to use a professional gallery with transitions etc, but the image sizes vary, and so the div size must be dynamic like the image sizes.  I was thinking of simply changing the contents of a div to change images.  Something like this:


<div id="imagediv"><img src="1.jpg" /></div>


--> *next* button is clicked


--> jQuery updates the div so that its contents become:


<div id="imagediv"><img src="2.jpg" /></div>


Is this possible?  If the image sizes are different, is this possible?  Cheers.

Link to comment
Share on other sites

I'm sure there is an existing slider solution that meets your requirements. I haven't tried it myself but Google found Sudo Slider with a dynamic height/width example here: http://webbies.dk/assets/files/SudoSlider/package/demos/autowidth%20centered.html


As for your idea to manually change the image in a div, I've written a jsfiddle (code below too) so you can see how this could be done in jQuery.  It might be a little involved if you have little or no jQuery/JavaScript experience but you'll have to hit the documentation sometime... 

<!doctype html>
<html lang="en">
	<meta charset="UTF-8">
	<title>Image Switch</title>

	<div id="container">
		<div id="product">			

			<ul id="controls">
				<li><a href="#" data-action="prev">Previous</a></li>
				<li><a href="#" data-action="next">Next</a></li>

			<div id="imagediv">
				<img src="http://placehold.it/100x150.png" alt="">

			<p>This is some information about the product</p>

			<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A, itaque, eveniet quae sunt aperiam beatae!</p>


	<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
	<script type="text/javascript">

		$(document).ready(function() {

			// The images that we want to cycle through...
			var images = ['http://placehold.it/100x150.png', 'http://placehold.it/200x200.png', 'http://placehold.it/150x150.png', 'http://placehold.it/300x100.png'];

			// The links that cycle the images
			var $controls = $('#controls a');

			// The image element
			var $image = $('#imagediv').find('img:first');

			$controls.click(function(e) {

				// The prev/next links don't actually go anywhere...

				// If for some reason there are no images...
				if ( ! images.length) return false;  

				// The link that's just been clicked
				var $link = $(this);

				// Which direction to cycle the images
				var action = $link.data('action') == 'next' ? 'next' : 'prev';

				// Find the position of our currently displayed image in the list of possible images
				var image_url = $image.attr('src');
				var image_index = $.inArray(image_url, images);  // $.inArray returns -1 if the item doesn't exist in the array to search

				// Calculate the position of the previous and next images relative to current image in the images array
				// (accounting for when the user hits "next" on the last image or "previous" on first image)
				var next_index = (image_index + 1 <= images.length - 1) ? image_index + 1 : 0;
				var prev_index = (image_index - 1 >= 0) ? image_index - 1 : images.length - 1;

				// Find the new image's URL using the images array
				var new_image = (action == 'next') ? images[next_index] : images[prev_index];				

				// Update the image element with the new image's URL
				$image.attr('src', new_image);


Link to comment
Share on other sites

That is fantastic.  Thank you for actually writing an entire script ... that's awesome.  So obviously you know what you're doing ...  Now what if I am pulling the images from a mysql database using php?  Can I just do a <?php echo $img; ?> within the javascript?


Can I do this?


echo "var images = ['" . $img1 . "', '" . $img2 . "'];";

Edited by xProteuSx
Link to comment
Share on other sites

As long as you produce valid/usable JavaScript with your PHP output, you should be ok.  If, like most people, you have JavaScript separate from your PHP and HTML then you could build an array of image URLs in PHP (after fetching from mysql) and then store this array as a JSON encoded data attribute. Something like this:


Build the array...


$images = array('http://placehold.it/100x150.png', 'http://placehold.it/200x200.png', 'http://placehold.it/150x150.png', 'http://placehold.it/300x100.png');


Add it to the markup (note the single quotes surrounding the data-image-list value)...

<div id="product" data-image-list='<?php echo json_encode($images); ?>'>
	<ul id="controls">
		<li><a href="#" data-action="prev">Prev Image</a></li>
		<li><a href="#" data-action="next">Next Image</a></li>
	<div id="imagediv">
		<img src="http://placehold.it/100x150.png" alt="" />
	<p>This is some information about the product</p>
	<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A, itaque, eveniet quae sunt aperiam beatae!</p>

Then access the image array and use it in your JavaScript...

$(document).ready(function() {

	var images = $('#product').data('imageList');

	// Now you should have an array of images to work with...
	// ...

Hope that helps...


Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.