Return to Snippet

Revision: 61836
at January 17, 2013 22:25 by vijayrajesh


Initial Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery Image Source Swap with attr function</title>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'><script  type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<style>
	body
	{
		margin	: 0;
		padding	: 0;
		background	: #EEE;
		color		: #333;
		font-family: 'Open Sans', sans-serif;
		font-size	: 12px;
		
	}
	#wrapper
	{
		width	: 1012px;
		margin	: 0 auto;
		 
	}
	
	.the-player
	{
		width	: 560px;
		height	: 315px;
		border	: 1px solid #333;
	}
	
	.embed-code
	{
		width	: 301px;
		height	: 85px;
	}
	
	
	.btn-img-swap
	{
		border: 1px solid #AAA;
		padding: 3px 5px;
		text-decoration: none;
		background: #333;
		color: #FFF;
	}
	
	.img1,.img2
	{
		width:200px;
		margin-right:20px;
	}
	
</style>
<body>
	<div id="wrapper">
	
		<h1>jQuery Image Source Swap with attr function</h1>
		
		 <img src="http://blog.pixelthemes.com/demo/jquery-image-swap/american-flag.jpg" class="img1" />
		 
		 <img src="http://blog.pixelthemes.com/demo/jquery-image-swap/colors-of-england.jpg" class="img2" />
		 
		 <div style="clear:both;"></div>
		 
		 <p><a href="#" class="btn-img-swap">Swap Images</a></p>
		
		<p>Demo by : <a href="http://blog.pixelthemes.com/">WordPress Themes</a> </br>
		Article Link : <a href="http://blog.pixelthemes.com/ideas/dynamically-load-youtube-video-iframe-embed-code-inside-a-div">Article on jQuery Image Source Swap with attr function</a>
	</div>
	
	<script type="text/javascript">
	$(document).ready(function() {
		$('.btn-img-swap').click(function() {
			 event.preventDefault(); 
			 var img_temp = $(".img1").attr("src");
			 $('.img1').attr("src",$('.img2').attr("src"));
			 $('.img2').attr("src",img_temp);
			});
		});
	</script>
</body>
</html>

Initial URL
http://blog.pixelthemes.com/ideas/jquery-image-source-swap-with-attr-function

Initial Description
I have made a small jQuery snippet to demo the image swapping with attr() funciton.  The demo uses 2 images with classes img1 and img2 respectively.  On a click of a button, the images are swapped.

Basically the script stores “src” value into a variable and then it is  used to swap 2 image sources.

Initial Title
jQuery Image Source Swap with attr() function

Initial Tags
image, jquery

Initial Language
jQuery