www.webdeveloper.com
Results 1 to 11 of 11

Thread: Switching images using JavaScript

  1. #1
    Join Date
    Jul 2014
    Posts
    15

    Switching images using JavaScript

    Hi everyone -

    I'm currently learning JavaScript at a university level (so still pretty basic level teachings) but I'm stumped on how to perform this request.

    Basically I have two images (one is a tiny blue ball and one is a tiny red ball) and a button "Change Color". They start out one Red and one Blue.

    I have to design it so it's changing the color of the balls. Starting with the color combination of two balls(blue,blue), any button click must lead to the following color combinations repeated cyclically: (blue,red), (red,blue), (red,red), then again (blue,blue)...

    Both balls have their own image file as well. I have the basic structure down to just switch between Red and blue over and over but I'm stumped at this point...any suggestions?

    Code:
    <script type="text/javascript">
    function lampSwitch() {
       var temp = document.images["left"].src;
       document.images["left"].src = 
           document.images["right"].src;
       document.images["right"].src = temp;
    }
    </script>
    <img src="ballred.gif" name="left" /> &nbsp;
    <img src="ballblue.gif" name="right" />
    <p>
    <form>
    <input type="button" value="Switch" 
        onclick="lampSwitch()" />
    </form>
    Thanks!

  2. #2
    Join Date
    Jun 2014
    Location
    Cairns - Australia
    Posts
    81
    Hey M,

    (joke).. Who's going to read the code?... Id cheat and make a 4 frames slideshow with a next button.. DONE!

    (real).. I understand.. You want a js that adjusts 2 images from 1 button... Theres a ton of scripts around to do that..

    My point is.. I would take the 1 button 2 image script & the slide show script.. and blend to make this script!...

    Thats what I would do and Id get it working... just suggesting outside the box, no biggy

  3. #3
    Join Date
    Jul 2014
    Posts
    15
    Quote Originally Posted by Code-tard View Post
    Hey M,

    (joke).. Who's going to read the code?... Id cheat and make a 4 frames slideshow with a next button.. DONE!

    (real).. I understand.. You want a js that adjusts 2 images from 1 button... Theres a ton of scripts around to do that..

    My point is.. I would take the 1 button 2 image script & the slide show script.. and blend to make this script!...

    Thats what I would do and Id get it working... just suggesting outside the box, no biggy
    To be honest, this course has been using teachings relevant from around 2003 so I'm not really learning good habits. So I'm not against this suggestion to be honest haha. To be honest though, I'm not 100% sure how to blend this current slideshow script either.

  4. #4
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,380
    Consider this modification ...

    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title> HTML5 page </title>
    </head>
    <body>
    <form>
    
    <!-- images not supplied, substitute your own -->
    <img src="http://www.freeimages.com/assets/182963/1829620214/red-ball-1184188-m.jpg" name="left"> &nbsp;
    <img src="http://www.rgbstock.com/cache1uhJyv/users/x/xy/xymonau/300/o0u2LzO.jpg" name="right">
    <p>
    
    <!-- original -->
      <input type="button" value="Switch" onclick="lampSwitch()" />
    <!-- -->
    <!-- modification -->
      <button onclick="return lampSequence()" id="btnSeq" value="0">Sequence</button>
    <!-- -->
    </form>
    
    <script type="text/javascript">
    
    // original code
    function lampSwitch() {
       var temp = document.images["left"].src;
       document.images["left"].src = document.images["right"].src;
       document.images["right"].src = temp;
    }
    
    // modified code
    var imageList = [
       'http://www.freeimages.com/assets/182963/1829620214/red-ball-1184188-m.jpg',
       'http://www.rgbstock.com/cache1uhJyv/users/x/xy/xymonau/300/o0u2LzO.jpg'
    ];
    var imageSequence = [ [0,0], [0,1], [1,0], [1,1] ];
    function lampSequence() {
       var seq = parseInt(document.getElementById('btnSeq').value);
       var lf = imageSequence[seq][0];
       var rt = imageSequence[seq][1];
       document.images["left"].src = imageList[lf];
       document.images["right"].src = imageList[rt];
       seq++;  seq = seq % (imageSequence.length);
       document.getElementById('btnSeq').value = seq;
    //   alert(seq+' : '+imageSequence.length+'\n'+imageList[lf]+'\n'+imageList[rt]);
       return false;
    }
    
    window.onload = function() { lampSequence(); }
    </script>
    </body>
    </html>
    Substitute your own images.

  5. #5
    Join Date
    Jul 2014
    Posts
    15
    Quote Originally Posted by JMRKER View Post
    Consider this modification ...

    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title> HTML5 page </title>
    </head>
    <body>
    <form>
    
    <!-- images not supplied, substitute your own -->
    <img src="http://www.freeimages.com/assets/182963/1829620214/red-ball-1184188-m.jpg" name="left"> *
    <img src="http://www.rgbstock.com/cache1uhJyv/users/x/xy/xymonau/300/o0u2LzO.jpg" name="right">
    <p>
    
    <!-- original -->
      <input type="button" value="Switch" onclick="lampSwitch()" />
    <!-- -->
    <!-- modification -->
      <button onclick="return lampSequence()" id="btnSeq" value="0">Sequence</button>
    <!-- -->
    </form>
    
    <script type="text/javascript">
    
    // original code
    function lampSwitch() {
       var temp = document.images["left"].src;
       document.images["left"].src = document.images["right"].src;
       document.images["right"].src = temp;
    }
    
    // modified code
    var imageList = [
       'http://www.freeimages.com/assets/182963/1829620214/red-ball-1184188-m.jpg',
       'http://www.rgbstock.com/cache1uhJyv/users/x/xy/xymonau/300/o0u2LzO.jpg'
    ];
    var imageSequence = [ [0,0], [0,1], [1,0], [1,1] ];
    function lampSequence() {
       var seq = parseInt(document.getElementById('btnSeq').value);
       var lf = imageSequence[seq][0];
       var rt = imageSequence[seq][1];
       document.images["left"].src = imageList[lf];
       document.images["right"].src = imageList[rt];
       seq++;  seq = seq % (imageSequence.length);
       document.getElementById('btnSeq').value = seq;
    //   alert(seq+' : '+imageSequence.length+'\n'+imageList[lf]+'\n'+imageList[rt]);
       return false;
    }
    
    window.onload = function() { lampSequence(); }
    </script>
    </body>
    </html>
    Substitute your own images.
    Appreciate that a lot JMRKER - I'm going to look over this for a bit first since your modifications made a lot of sense.

    Thanks!

  6. #6
    Join Date
    May 2014
    Posts
    936
    Some advice:

    1) if your elements only work when scripting is on, they don't belong in the markup.

    2) Swaps like this are usually handled better by just swapping the class.

    3) and work better if you were to let CSS handle it through something like sprites.

    4) There's no reason to wait for onload.

    5) It's also not a great idea to abuse form elements for scripting outside of forms.

    6) Binary math would REALLY simplify matters, since if you did

    state = (state + 1) % 3;

    it would return values 0..3 in sequence.

    0 == 00
    1 == 01
    2 == 10
    3 == 11

    You could then just "& 1" and "& 2" to pull the corresponding bit.

    Which is why if I was doing this, the body markup would look like this:

    Code:
    <div id="top">
    	<h1>Color switching demo</h1>
    	<noscript>
    		<p>
    			This page requires JavaScript to function. Please enable it or use a browser that supports it.
    		</p>
    	</noscript>
    <!-- #top --></div>
    the scripting would go something like this.

    Code:
    (function(d) {
    
    	function make(tagName, content, attribs, parent) {
    		var e = d.createElement(tagName);
    		if (content) e.appendChild(
    			typeof content == 'object' ? content : d.createTextNode(content)
    		);
    		if (attribs) for (var i in attribs) e[i] = attribs[i];
    		if (parent) parent.appendChild(e);
    		return e;
    	}
    	
    	function prevent(e) {
    		e.cancelBubble = true;
    		if (e.stopPropagation) e.stopPropagation();
    		if (e.preventDefault) e.preventDefault();
    		e.returnValue = false;
    	}
    	
    	function noSelect(t) {
    		if (window.getSelection) window.getSelection().removeAllRanges();
    		if (d.selection) d.selection.empty();
    		t.blur();
    	}
    
    	var
    		state = 0,
    		top = d.getElementById('top'),
    		ball0 = make('span', false, { className : 'blueBall' }, top),
    		ball1 = make('span', false, { className : 'blueBall' }, top);
    		
    	make('br', false, false, top);
    	make('a', 'Update', {
    		className : 'updateButton',
    		href : 'javascript:void(0);',
    		onclick : function(e) {
    			e = e || window.event;
    			var t = e.target || e.srcElement;
    			state = (state + 1) & 3;
    			ball0.className = (state & 1) ? 'redBall' : 'blueBall';
    			ball1.className = (state & 2) ? 'redBall' : 'blueBall';
    			prevent(e);
    			noSelect(t);
    		}
    	}, top);
    	
    })(document);
    Which I put a live demo of up here:
    http://www.cutcodedown.com/for_other.../template.html

    As with all my examples the directory:
    http://www.cutcodedown.com/for_others/Minnesota31/

    Is unlocked for easy access to the gooey bits and pieces.

    The real magic is that it uses just one image, so the second is pre-cached and swaps faster/smoother:
    http://www.cutcodedown.com/for_other...ages/balls.png

    Loaded into a span thus:
    Code:
    .blueBall,
    .redBall {
    	display:inline-block;
    	width:48px;
    	height:48px;
    	margin-right:8px;
    	background:url(images/balls.png) 0 0 no-repeat;
    }
    
    .redBall {
    	background-position:0 -50px;
    }
    I put 2px of separation between the 'sprite tiles' so that on zoom crappy browsers don't accidentally show a bit of the wrong image.

    Hope this helps.
    Java is to JavaScript as Ham is to Hamburger.

  7. #7
    Join Date
    Nov 2010
    Posts
    1,085
    you can also do it with divs, provided you don't care about old IE. Otherwise the changeIt function can be modified to use src on the img tags...
    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <style>
    .ball {
    	border-radius: 50%;
    	width: 200px;
    	height: 200px;
    	display:inline-block;	
    	background-color:blue;
    	}
    
    </style>
    </head>
    <body>
    <div class="ball" id="left"></div>
    <div class="ball" id="right"></div>
    <input type="button" id="changer" value="switch"/>
    <script type="text/javascript">
    
    (function (){
    var count = 0, l=document.getElementById("left"), r = document.getElementById("right");
    document.getElementById("changer").onclick=function(){
    if(++count%2==0){
    changeIt(l);
    }
    changeIt(r);
    }
    
    function changeIt(el){
    el.style.backgroundColor=el.style.backgroundColor!="red"?"red":"blue";
    }
    })();
    </script>
    </body>
    </html>

  8. #8
    Join Date
    May 2014
    Posts
    936
    @xelawho -- I like this:

    if (++count%2==0)

    cute trick since if bit 1 is set you are flipping the first, otherwise the second. slick.

    That could probably be simplified down to:

    changeIt( (++count % 2 == 0) ? l : r );

    Though the el.style.backgroundColor part may be unreliable cross-browser; not all browsers return the word when you use a named color.
    Java is to JavaScript as Ham is to Hamburger.

  9. #9
    Join Date
    Nov 2010
    Posts
    1,085
    Quote Originally Posted by deathshadow View Post

    if bit 1 is set you are flipping the first, otherwise the second. slick.

    That could probably be simplified down to:

    changeIt( (++count % 2 == 0) ? l : r );
    almost, but not - it's not a straight if/else. Have a look at the pattern:

    B B
    B R
    R B
    R R
    B B
    B R
    R B
    R R
    B B
    ... etc...

    the left side flips after the second click whereas the right side flips every time.

    just out of curiosity, could you tell me which browsers don't return a named color if a named color has been set? I know it's lazy, but it works on all my browsers

  10. #10
    Join Date
    Mar 2012
    Posts
    1,560
    Quote Originally Posted by xelawho View Post
    almost, but not - it's not a straight if/else. Have a look at the pattern:

    B B
    B R
    R B
    R R
    B B
    B R
    R B
    R R
    B B
    ... etc...

    the left side flips after the second click whereas the right side flips every time.
    DS is right . Substitute B=0 and R=1 and you get:

    BB = 00
    BR = 01
    RB = 10
    RR = 11
    etc...

  11. #11
    Join Date
    May 2014
    Posts
    936
    Actually xelawho's right, I missed the lack of else... the way I wrote it it would:

    00 == BB
    01 == BR
    10 == RR (we didn't change the first one)
    11 == RB

    Because it's only changing one or the other, not both.
    Java is to JavaScript as Ham is to Hamburger.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles