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

dalearyous

Senior member
Jan 8, 2006
836
0
0
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?
 

Woosta

Platinum Member
Mar 23, 2008
2,978
0
71
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:

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,631
4,559
75
I'll also note that "$('IMG1')" is a JQuery thing, not a "simple javascript" thing. "document.getElementById('IMG1')" is the "simple javascript" equivalent.
 

Woosta

Platinum Member
Mar 23, 2008
2,978
0
71
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.
 

dalearyous

Senior member
Jan 8, 2006
836
0
0
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:

PhatoseAlpha

Platinum Member
Apr 10, 2005
2,131
21
81
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?
 

PhatoseAlpha

Platinum Member
Apr 10, 2005
2,131
21
81
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:

SJP0tato

Senior member
Aug 19, 2004
267
0
76
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!
 

Woosta

Platinum Member
Mar 23, 2008
2,978
0
71
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.
 

SJP0tato

Senior member
Aug 19, 2004
267
0
76
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.
 

upperkingjr

Junior Member
Jan 25, 2014
1
0
0
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:

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
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.
 

ejjpi

Member
Dec 21, 2013
58
0
0
pangoly.com
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>