Change image source with JavaScript

So I'm new with JavaScript (this is actually my first attempt to make something work) and I'm having a bit of trouble. I thought I had enough knowledge to make this work, I've even googled for tutorials and scripts that could help me work this out but nothing really helped.

I can't seem to change the image source, heres the code that I have so far:

<script type="text/javascript">
    function changeImage(a) {
        document.getElementById("img").src=a.src;
    }
</script>
<div id="main_img">
    <img id="img" src="1772031_29_b.jpg">
</div>
<div id="thumb_img">
    <img src='1772031_29_t.jpg'  onclick='changeImage("1772031_29_b.jpg");'>
    <img src='1772031_55_t.jpg'  onclick='changeImage("1772031_55_b.jpg");'>
    <img src='1772031_53_t.jpg'  onclick='changeImage("1772031_53_b.jpg");'>
</div>

Could anyone please explain if I'm doing something wrong? Or maybe I'm missing something? Help me please :-)

Answers


function changeImage(a) so there is no such thing as a.src => just use a.

demo here


If you will always have the pattern on _b instead of _t you can make it more generic by passing reference to the image itself:

onclick='changeImage(this);'

Then in the function:

function changeImage(img) {
    document.getElementById("img").src = img.src.replace("_t", "_b");
}

Your only real problem is you are passing a string, not an object with a .src property

Some suggestions:

  • Use a naturally clickable element trigger, such as <button>
  • Use data- prefixed attributes for event data on the element
  • Use late bound events when the DOM is ready.

Markup:

<div id="main_img">
  <img id="img" src="1772031_29_b.jpg">
</div>
<ul id="thumb_img">
  <li><button data-src='1772031_29_b.jpg'><img src='1772031_29_t.jpg' /></button></li>
  <li><button data-src='1772031_55_b.jpg'><img src='1772031_55_t.jpg' /></button></li>
  <li><button data-src='1772031_53_b.jpg'><img src='1772031_53_t.jpg' /></button></li>
</ul>

JavaScript:

If you need to support IE and other legacy browsers, Use a proper polyfill for Array.from

function clickedButton(btn, event) {
  document.getElementById('img').src = btn.getAttribute('data-src');
}

function bindClick(btn) {
  btn.addEventListener('click', clickedButton.bind(null,btn));
}

// Setup click handler(s) when content is loaded
document.addEventListener("DOMContentLoaded", function(){
  Array.from(document.querySelectorAll('#thumb_img > button'))
    .forEach(bindClick));
});

Edit: Vanilla JS for modern browsers.


You've got a few changes (this assumes you indeed still want to change the image with an ID of IMG, if not use Shadow Wizard's solution).

Remove a.src and replace with a:

<script type="text/javascript">
function changeImage(a) {
    document.getElementById("img").src=a;
}
</script>

Change your onclick attributes to include a string of the new image source instead of a literal:

onclick='changeImage( "1772031_29_b.jpg" );'

I also tube that problem. But solve it by an instance of an image every time you change the source (image).

It seems that would be called onload only once. But this way, you can change image whenever you want.

function chageIcon(domImg,srcImage)
    {
        var img = new Image();
        img.onload = function()
        {
            // Load completed
            domImg.src = this.src;
        };
        img.src = srcImage;
    }

Mode use.

chageIcon(document.getElementById("img"),"newIcon.png");

The problem was that you were using .src without needing it and you also needed to differentiate which img you wanted to change.

function changeImage(a, imgid) {
    document.getElementById(imgid).src=a;
}
<div id="main_img">
    <img id="img" src="1772031_29_b.jpg">
</div>
<div id="thumb_img">
    <img id="1" src='1772031_29_t.jpg'  onclick='changeImage("1772031_29_b.jpg", "1");'>
    <img id="2" src='1772031_55_t.jpg'  onclick='changeImage("1772031_55_b.jpg", "2");'>
    <img id="3" src='1772031_53_t.jpg'  onclick='changeImage("1772031_53_b.jpg", "3");'>
</div>

The Following Example Program used to change the image src attribute for every 100 milliseconds. you may call the given function as your wish.

<html>
<head>
</head>
<body>
<img src="bulboff.jpg" height=200 width=200 id="imm" align="right">

<script type="text/javascript">

function bulb() {

var b = document.getElementById("imm");

if(b.src.match("bulboff.jpg")) {
 b.src = "bulbon.jpg";
}
 else {

 b.src="bulboff.jpg";
}
}
 setInterval(bulb,100);
</script>
</body>
</html>

Instead of writing this,

<script type="text/javascript">
function changeImage(a) {
    document.getElementById("img").src=a.src;
}
</script>

try:

<script type="text/javascript">
function changeImage(a) {
document.getElementById("img").src=a;
}
</script>

 <script type="text/javascript">
        function changeImage(a) {
    var picName=a.substring(1,a.length-1);
            document.getElementById("image").src=picName;
        }
 </script>

 <div id="main_img">
     <img id="image" src="app.jpg">
 </div>

 <div id="thumb_img">
     <img src='app.jpg'  onclick="changeImage('+5steps.jpg+');">
     <img src='5steps.jpg'  onclick="changeImage('+award.png+');">
     <img src='award.png'  onclick="changeImage('+app.jpg+');">
 </div>

Use the above code by placing this html file and pics(take care in namings, beacause I have given the above code with my pic names) in same folder you will get...


Hi i tried to integrate with your code.

Can you have a look at this?

Thanks M.S

<!DOCTYPE html>
<html>
<head>

<!--TODO: need to integrate this code into the project to change images added 05/21/2016:-->

<script type="text/javascript">
    function changeImage(a) {
        document.getElementById("img").src=a;
    }
</script>


	
<title> Fluid Selection </title>
<!-- css -->
	<link rel="stylesheet" href="bootstrap-3/css/bootstrap.min.css">
	<link rel="stylesheet" href="css/main.css">
<!-- end css -->
<!-- Java script files -->
<!-- Date.js date os javascript helper -->
    <script src="js/date.js"> </script>

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
	<script src="js/jquery-2.1.1.min.js"></script>

<!-- Include all compiled plugins (below), or include individual files as needed -->
	<script src="bootstrap-3/js/bootstrap.min.js"> </script>
	<script src="js/library.js"> </script>
	<script src="js/sfds.js"> </script>
	<script src="js/main.js"> </script>

<!-- End Java script files -->

<!--added on 05/28/2016-->

<style>
/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index:40001; /* High z-index to ensure it appears above all content */ 
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
   
    background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    position: relative;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    width: 40%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s
	opacity:.5; /* Sets opacity so it's partly transparent */ -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; 
	/* IE 				
	transparency */ filter:alpha(opacity=50); /* More IE transparency */ z-index:40001; } 
}

/* Add Animation */
@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0} 
    to {top:0; opacity:1}
}

@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}

/* The Close Button */
.close {
    
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor:pointer;
}

/* The Close Button */
.close2 {
    
}


.close2:focus {
    color: #000;
    text-decoration: none;
    cursor:pointer;
}

.modal-header {
	color: #000;
    padding: 2px 16px;
 }

.modal-body {padding: 2px 16px;}
	
	
}

.modal-footer {
    padding: 2px 16px;
    background-color: #000099;
    color: white;
}


</style>

<script>
	$(document).ready(function() {
	
	
		$("#water").click(function(event){
			var $this= $(this);
			if($this.hasClass('clicked')){
				$this.removeClass('clicked');
				SFDS.setFluidType(0);
				$this.find('h3').text('Select the H20 Fluid Type');
				}else{
					SFDS.setFluidType(1);
					$this.addClass('clicked');
					$this.find('h3').text('H20 Selected');

			}
		});
		
		$("#saline").click(function(event){
			var $this= $(this);
			if($this.hasClass('clicked')){
				$this.removeClass('clicked');
				SFDS.setFluidType(0);
				$this.find('h3').text('Select the NaCL Fluid Type');
				}else{
					SFDS.setFluidType(1);
					$this.addClass('clicked');
					$this.find('h3').text('NaCL Selected');
					
		
		
			}
		});
		
	});
</script>
</head>
<body>
<div class="container-fluid">
	<header>
		<div class="row">
			<div class="col-xs-6">
				<div id="date"><span class="date_time"></span></div>
			</div>
			<div class="col-xs-6">
				<div id="time" class="text-right"><span class="date_time"></span></div>
			</div>
		</div>
	</header>

	<div class="row">
		<div class="col-md-offset-1 col-sm-3 col-xs-8 col-xs-offset-2 col-sm-offset-0">
			<div id="fluid" class="main_button center-block">
				<div class="large_circle_button, main_img"> 
					<h2>Select<br>Fluid</h2>
					<img class="center-block large_button_image" src="images/dropwater.png" alt=""/> 
				</div>
				<h1></h1>
			</div>
		</div>
		<div class=" col-md-6 col-sm-offset-1 col-sm-8 col-xs-12">
			<div class="row">
				<div class="col-xs-12">
					<div id="water" class="large_rectangle_button">
						<div class="label_wrapper">
							<h3>Sterile<br>Water</h3>
						</div>
						<div id="thumb_img" class="image_wrapper">
							<img src="images/dropsterilewater.png" alt="Sterile Water" class="sterile_water_image" onclick='changeImage("images/dropsterilewater.png");'>
						</div>
						<img src="images/checkmark.png" class="button_checkmark" width="96" height="88">
					</div>
				</div>
				<div class="col-xs-12">
					<div id="saline" class="large_rectangle_button">
						<div class="label_wrapper">
							<h3>Sterile<br>0.9% NaCL</h3>
						</div>
						<div class="image_wrapper">
							<img src="images/cansterilesaline.png" alt= "Sterile Saline" class="sterile_salt_image" onclick='changeImage("images/imagecansterilesaline.png");'>
						</div>
						<img src="images/checkmark.png" class="button_checkmark" width="96" height="88">

					</div>
				</div>
				<div class="col-xs-12">
					<div class="small_rectangle_button">
						
						<!-- Trigger/Open The Modal -->
						<div id="myBtn" class="label_wrapper">
							<h3>Change<br>Cartridge</h3>
						</div>
						<div class="image_wrapper">
							<img src="images/changecartridge.png" alt="" class="change_cartrige_image" />
						</div>
					</div>
				</div>
				
					<!-- The Modal -->
					<div id="myModal" class="modal">

					  <!-- Modal content -->
					  <div class="modal-content">
						<div class="modal-header">
						  <span class="close"><img src="images/x-icon.png"></span>
						  <h2>Change Cartridge Instructions</h2>
						</div>
						<div class="modal-body">
						  <h4>Lorem ipsum dolor sit amet, dicant nonumes volutpat cu eum, in nulla molestie vim, nec probo option iracundia ut. Tale inermis scripserit ne cum, his no errem minimum commune, usu accumsan omnesque in. Eu has nihil dolor debitis, ad nobis impedit per. Dicat mnesarchum quo at, debet abhorreant consectetuer sea te, postea adversarium et eos. At alii dicit his, liber tantas suscipit sea in, id pri erat probatus. Vel nostro periculis dissentiet te, ut ubique noster vix. Id honestatis disputationi vel, ne vix assum constituam.</h4>                                                   
                           <a href="#"><img src="images/video-icon.png" alt="click here for video">	</a>
                           <a href="#close2" title="Close" class="close2"><img src="images/cancel-icon.png" alt="Cancel"></a>

                          
						</div>
						<div class="modal-footer">
						  <h4></h4>
						</div>
					  </div>

					</div>
					
					<!--for comparison-->


					

					
					<script>
					// Get the modal
					var modal = document.getElementById('myModal');

					// Get the button that opens the modal
					var btn = document.getElementById("myBtn");

					// Get the <span> element that closes the modal
					var span = document.getElementsByClassName("close")[0];
					

					// When the user clicks the button, open the modal 
					btn.onclick = function() {
						modal.style.display = "block";
					}

					// When the user clicks on <span> (x), close the modal
					span.onclick = function() {
						modal.style.display = "none";
					}

					// When the user clicks anywhere outside of the modal, close it
					window.onclick = function(event) {
						if (event.target == modal) {
							modal.style.display = "none";
						}
						
						
					}
					</script>
                    

				
				
				
				
				
			</div>
		</div>
	</div>
</div>
<footer class="footer navbar-fixed-bottom">
	<div class="container-fluid">
		<div class="row cols-bottom">
			<div class="col-sm-3">
				<a href="main.html">
				<div class="small_circle_button">					
					<img src="images/buttonback.png" alt="back to home" class="settings"/> <!--  width="49" height="48" -->
				</div>
			</div></a><div class=" col-sm-6">
				<div id="stop_button" >
					<img src="images/stop.png" alt="stop" class="center-block stop_button" /> <!-- width="140" height="128" -->
				</div>
					
			</div><div class="col-sm-3">
				<div id="parker" class="pull-right">
					<img src="images/parkerlogo.png" alt="parkerlogo" /> <!-- width="131" height="65" -->
				</div>
			</div>
		</div>
	</div>
</footer>


</body>
</html>

Under the TODOs, i am trying to implement your code in this posting. I am trying to take the large div on the left and make it change to reflect selections on the right. there are two selections, Ambient Temperature and Body Temperature

<!DOCTYPE html>
<html>
<head>
<title> Temperature Selection </title>
<!-- css -->
	<link rel="stylesheet" href="bootstrap-3/css/bootstrap.min.css">
	<link rel="stylesheet" href="css/main.css">

<!-- end css -->
<!-- Java script files -->
<!-- Date.js date os javascript helper -->
    <script src="js/date.js"> </script>

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
	<script src="js/jquery-2.1.1.min.js"></script>

<!-- Include all compiled plugins (below), or include individual files as needed -->
	<script src="bootstrap-3/js/bootstrap.min.js"> </script>
	<script src="js/library.js"> </script>
	<script src="js/sfds.js"> </script>

	<script src="js/main.js"> </script>

<!-- End Java script files -->

<!--TODO: need to integrate this code into the project:-->
<script type="text/javascript">
    function changeImage(a) {
        document.getElementById("img").src=a;
    }
</script>
	<script>
	
	
	$(document).ready(function() {
	
		$("#ambient").click(function(event){
			var $this= $(this);
			if($this.hasClass('clicked')){
				$this.removeClass('clicked');
				SFDS.setTemperatureType(0);
				$this.find('h2').text('Select Ambient Temperature 21 Degrees C');
				<!--added on 05/20/2015-->
			}else{
				SFDS.setTemperatureType(1);
				$this.addClass('clicked');
				$this.find('h2').text('Ambient Temperature 21 Degrees C Selected');


			}
		});
		
		$("#body").click(function(event){
			var $this= $(this);
			if($this.hasClass('clicked')){
				$this.removeClass('clicked');
				SFDS.setTemperatureType(0);
				$this.find('h2').text('Select Body Temperature 37 Degrees C');
				<!--added on 05/20/2015-->
			}else{
				SFDS.setTemperatureType(1);
				$this.addClass('clicked');
				$this.find('h2').text('Body Temperature 37 Degrees C Selected');


			}
		});
		
		
		
	});
</script>

</head>
<body>
<div class="container-fluid">
	<header>
		<div class="row">
			<div class="col-xs-6">
				<div id="date"><span class="date_time"></span></div>
			</div>
			<div class="col-xs-6">
				<div id="time" class="text-right"><span class="date_time"></span></div>
			</div>
		</div>
	</header>
	<div class="row">
		<div class="col-md-offset-1 col-sm-3 col-xs-8 col-xs-offset-2 col-sm-offset-0">
			<div id="temperature" class="main_button center-block">
				<div class="large_circle_button"> 
					<h2>Select<br/>Temperature</h2>
					<img class="center-block large_button_image" src="images/thermometer.png" alt=""> 
                    <!-- TODO <img src='images/dropsterilewater.png'  onclick='changeImage("images/dropsterilewater.png");'>
                                <img src='images/imagecansterilesaline.png'  onclick='changeImage("images/imagecansterilesaline.png");'>-->
				</div>
				<h1></h1>
			</div>
		</div>
		<div class=" col-md-6 col-sm-offset-1 col-sm-8 col-xs-12">
			<div class="row">
				<div class="col-xs-12">
					<div id="ambient" class="large_rectangle_button">
						<div class="label_wrapper">
							<h2>Ambient<br/>Temperature<br/>21<sup>o</sup>C</h2>
						</div>
						<div class="image_wrapper">
							<img src="images/house.png" alt="" class="ambient_temp_image">
						</div>
						<img src="images/checkmark.png" class="button_checkmark" width="96" height="88">

					</div>
				</div>
				<div class="col-xs-12">
					<div id="body" class="large_rectangle_button">
						<div class="label_wrapper">
							<h2>Body<br/>Temperature<br/>37<sup>o</sup>C</h2>
						</div>
						<div class="image_wrapper">
							<img src="images/bodytempman.png" alt="" class="body_temp_image">
						</div>
						<img src="images/checkmark.png" class="button_checkmark" width="96" height="88">

					</div>
				</div>
			</div>
		</div>
	</div>

				
</div>
<footer class="footer navbar-fixed-bottom">
	<div class="container-fluid">
		<div class="row cols-bottom">
			<div class="col-sm-3">
				<a href="main.html">
				<div class="small_circle_button">					
					<img src="images/buttonback.png" alt="back to home" class="settings"/> <!--  width="49" height="48" -->
				</div>
			</div></a><div class=" col-sm-6">
				<div id="stop_button" >
					<img src="images/stop.png" alt="stop" class="center-block stop_button" /> <!-- width="140" height="128" -->
				</div>
					
			</div><div class="col-sm-3">
				<div id="parker" class="pull-right">
					<img src="images/#" alt="logo" /> <!-- width="131" height="65" -->
				</div>
			</div>
		</div>
	</div>
</footer>


</body>
</html>

Try this!

function changeimage() {
    var image = document.getElementById('imagem');
    if (image.src.match("img")) {
        for(i = 1; i <= 3; i++) {
            image.src = "img/image2"+i+".png";
        }
    } else {
        image.src = "img/image1.png";
    }
}

Need Your Help

UITableView with Transparent Gradient at Top and Bottom

iphone ios uitableview core-graphics calayer

I have searched this forum, Google and other forums and have not found an the answer to my particular issue.

How to extract shape coordinates in Word VBA

vba ms-word visio

I'm trying to write a VBA macro in Word that will extract shapes and build them in Visio. I'm having some trouble getting the X Y coordinates of the shape in the document. I have tried using the T...