• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

swapImage(); simple javascript doesn't work. help

dalearyous

Senior member
Code:
<SCRIPT LANGUAGE=JavaScript>
function swapImage()
{
switch (intImage) 
{
    case 1:
        $('IMG1').src = "images/front_cover.jpg"
        intImage = 2
        return(false);
    case 2:
         $('IMG1').src ="images/back_cover.jpg"
        intImage = 1
    return(false);
}
}
</SCRIPT>

and then the html that calls this is:

Code:
<img  id="IMG1" name="IMG1" onclick="swapImage();" src="images/front_cover.jpg" ...

whats wrong with this?
 
Your function does a switch on intImage. It is never initially defined, and there is no default in the switch. So either specify a default, or set an initial value for intImage.

Ideally you want to not rely on inline event handlers so I suggest removing onclick="" and putting this before the end body tag:

Code:
<script>
(function() {

var intImage = 1;

function swapImage(){
  switch ( intImage ) {
      case 1:
          // do stuff
      break;
      case 2:
          //do stuff
      break;
      default: 
          // default stuff
  }
} 

window.onload = function(){ 
   var img = document.getElementById('IMG1');
   img.onclick = swapImage;
   
}

})();
</script>
 
Last edited:
I'll also note that "$('IMG1')" is a JQuery thing, not a "simple javascript" thing. "document.getElementById('IMG1')" is the "simple javascript" equivalent.
 
I think he might've changed his code or I read wrong initially, Ken_g6 is right.

It would be
Code:
$('#IMG1').attr('src', 'newsrc')

If it's jQuery. If it's another library that only supports the ID without the hash then nevermind.
 
so, combining woosta example using the simple javascript document.getElementById instead would look like what?

Code:
<script>
(function() {

var intImage = 1;

function swapImage(){
  switch ( intImage ) {
      case 1:
          document.getElementById('IMG1').src="front_thumb.jpg"
		  intImage = 2;
		  return(false);
      break;
      case 2:
          document.getElementById('IMG1').src="back_thumb.jpg"
		  intImage = 1;
		  return(false);
      break;
      default: 
          document.getElementById('IMG1').src="front_thumb.jpg"
  }
} 

window.onload = function(){ 
   var img = document.getElementById('IMG1');
   img.onclick = swapImage;
   
}

})();
</script>


using this:
<img id="IMG1" src="front_thumb.jpg" width="50" height="75" />

*edit*
works!

can i var img = document.getElementById('IMG1'); and get more than one? basically i want more than 1 image making this swap happen
 
Last edited:
getElementById returns only a single unique element. When you say you want more then 1 image making the swap happen, do you mean there are, for example 3 images, and if you click on one all three change to the same image?
 
A generalized version. Replace the values in IDs with your element IDs, the URLs in URLs with your URLS, add in more if needed.

Code:
<script type='text/javascript'>
var IDs = ['IMG1', 'IMG2', 'IMG3'];
var URLS = ['front_thumb.jpg', 'back_thumb.jpg'];
var elements = [];
var currentURL = 0;


function swapImage()
{
	currentURL += 1;
	if (currentURL >= URLS.length)
		{
		currentURL = 0;
		}
	for (var t=0;t<IDs.length;t++)
	{
		elements[t].src = URLS[currentURL];
	}
		
}

window.onload = function()
{
	for (var t=0;t<IDs.length;t++)
	{
		elements[t] = document.getElementById(IDs[t]);
		elements[t].onclick=swapImage;
	}
}
</script>
Fairly straightforward. Element IDs are in an array, then the elements themselves get stored in a separate array so as to prevent getting them every time. URLs are also in an array, on a click it changes all images to the next URL in the URL array. Checks are done versus array length, so you can add in more elements/URLs without breaking anything.
 
Last edited:
Ideally you want to not rely on inline event handlers so I suggest...

Why is this? Do you mean specifically for this instance it's not a best practice, or in general?

It's not often I hear about best practices for Javascript (usually it's the opposite) so I'm curious what the reasoning is.

Thanks!
 
Why is this? Do you mean specifically for this instance it's not a best practice, or in general?

It's not often I hear about best practices for Javascript (usually it's the opposite) so I'm curious what the reasoning is.

Thanks!

In general, you should separate presentation ( css ) vs content ( html ) vs behaviour ( js ). One should put js in .js, css in .css, and only reference them in .html and not actually have inline styles or inline behaviour.
 
In general, you should separate presentation ( css ) vs content ( html ) vs behaviour ( js ). One should put js in .js, css in .css, and only reference them in .html and not actually have inline styles or inline behaviour.

Okay, that makes sense & I agree.

I wasn't sure if maybe it was something about the usage of the inline event handlers that was deprecated or somesuch.
 
A generalized version. Replace the values in IDs with your element IDs, the URLs in URLs with your URLS, add in more if needed.

Code:
<script type='text/javascript'>
var IDs = ['IMG1', 'IMG2', 'IMG3'];
var URLS = ['front_thumb.jpg', 'back_thumb.jpg'];
var elements = [];
var currentURL = 0;


function swapImage()
{
	currentURL += 1;
	if (currentURL >= URLS.length)
		{
		currentURL = 0;
		}
	for (var t=0;t<IDs.length;t++)
	{
		elements[t].src = URLS[currentURL];
	}
		
}

window.onload = function()
{
	for (var t=0;t<IDs.length;t++)
	{
		elements[t] = document.getElementById(IDs[t]);
		elements[t].onclick=swapImage;
	}
}
</script>
Fairly straightforward. Element IDs are in an array, then the elements themselves get stored in a separate array so as to prevent getting them every time. URLs are also in an array, on a click it changes all images to the next URL in the URL array. Checks are done versus array length, so you can add in more elements/URLs without breaking anything.

please be more specific.
I want this code to change more than one separate images at the same time using multiple sources like the code below

Code:
<select id="dd" onChange="swapImage()">
<option value="http://deladream.com/wp-content/uploads/2010/11/1984.jpg">None Selected</option>
<option value="http://131940.qld.gov.au/DMR.Controls/WebCams/DisplayImage.ashx?FilePath=Metropolitan/Upper_MtGravatt_Pac_Mwy_Nth.jpg&35170044">Upper Mount Gravatt - Pacific Motorway and Klumpp Road (North)</option>
<option value="http://131940.qld.gov.au/DMR.Controls/WebCams/DisplayImage.ashx?FilePath=\Metropolitan\MRMETRO-1224.jpg&78465240">Kenmore - Moggill Road - Kenmore Road (East)</option>
<option value="http://131940.qld.gov.au/DMR.Controls/WebCams/DisplayImage.ashx?FilePath=\Metropolitan\MRMETRO-1213.jpg&2039636175">Chermside - Gympie Road - Webster Road (South-East)</option>
<option value="http://131940.qld.gov.au//DMR.Controls/WebCams/DisplayImage.ashx?FilePath=\Metropolitan\MRMETRO-1214.jpg&2144911343">Woolloongabba - Pacific Motorway</option>
<option value="http://131940.qld.gov.au//DMR.Controls/WebCams/DisplayImage.ashx?FilePath=\Metropolitan\MRMETRO-1458.jpg&1568524335">Archerfield - Beaudesert Road and Granard Road (East)</option>
<option value="http://www.cctv.com/Library/dcs_tag.js">Chinese Pandas</option>
</select>

<img id="imageToSwap" src="http://deladream.com/wp-content/uploads/2010/11/1984.jpg">
<img id="image2ToSwap" src="http://upperboards.com/ubh/images/signup.gif" />



<script type="text/javascript">
var arr = [];
arr['http://deladream.com/wp-content/uploads/2010/11/1984.jpg'] = '';
arr['http://upperboards.com/ubh/images/signup.gif'] = '';

//create a map with all d options..


function swapImage(){
    var image = document.getElementById("imageToSwap");
    var image2 = document.getElementById("image2ToSwap");
    var dropd = document.getElementById("dd");
    image.src = dropd.value;    
    image2.src=arr[dropd.value];

};
</script>
 
Last edited:
In general, you should separate presentation ( css ) vs content ( html ) vs behaviour ( js ). One should put js in .js, css in .css, and only reference them in .html and not actually have inline styles or inline behaviour.

If people would actually do this my life would be sunny and pleasant.
 
please be more specific.
I want this code to change more than one separate images at the same time using multiple sources like the code below

what the hell, reading this forum it's like jumping back in the 90's lol.

Here's how you do it:

HTML:
Code:
<select id="dd">
<option value="http://deladream.com/wp-content/uploads/2010/11/1984.jpg">None Selected</option>
<option value="http://131940.qld.gov.au/DMR.Controls/WebCams/DisplayImage.ashx?FilePath=Metropolitan/Upper_MtGravatt_Pac_Mwy_Nth.jpg&35170044">Upper Mount Gravatt - Pacific Motorway and Klumpp Road (North)</option>
<option value="http://131940.qld.gov.au/DMR.Controls/WebCams/DisplayImage.ashx?FilePath=\Metropolitan\MRMETRO-1224.jpg&78465240">Kenmore - Moggill Road - Kenmore Road (East)</option>
<option value="http://131940.qld.gov.au/DMR.Controls/WebCams/DisplayImage.ashx?FilePath=\Metropolitan\MRMETRO-1213.jpg&2039636175">Chermside - Gympie Road - Webster Road (South-East)</option>
<option value="http://131940.qld.gov.au//DMR.Controls/WebCams/DisplayImage.ashx?FilePath=\Metropolitan\MRMETRO-1214.jpg&2144911343">Woolloongabba - Pacific Motorway</option>
<option value="http://131940.qld.gov.au//DMR.Controls/WebCams/DisplayImage.ashx?FilePath=\Metropolitan\MRMETRO-1458.jpg&1568524335">Archerfield - Beaudesert Road and Granard Road (East)</option>
<option value="http://www.cctv.com/Library/dcs_tag.js">Chinese Pandas</option>
</select>

<img id="imageToSwap" class="imageSwap">
<img id="image2ToSwap" class="imageSwap">
JS:
Code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $("#dd").change(function() {
            $(".imageSwap").attr("src", $(this).val());
        });
    });
</script>
 
Back
Top