SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 41
  1. #1
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How can you traverse an arry with onclick?

    Hi Guys,

    I'm working on an image gallery at the moment and I'm having some trouble with the array the the images are stored in.

    The issue I'm having is that I can't figure out how to increase and decrease the current element in an array with the onclick event.

    Here's what I'm thinking so far:

    var imageList = ['a','b','c','d','e'];
    var position=0;
    currentImage=imageList[position];

    if a link with the id of "leftClick" is clicked, then position should decrease by 1
    but if a link with the id of "rightClick" is clicked, then position should increase by 1

    Both of these conditions should be bound to imageList.length
    i.e. if (position<0){position=0};
    and if (position>imageList.length){position=imageList.length};

    So how can I make "position" increase or decrease by clicking a link using the onclick event?

    Any help would be appreciated.

    regards
    Steve

  2. #2
    We're from teh basements.
    Join Date
    Apr 2007
    Posts
    1,205
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You can determine which button was clicked in your event handler. This varies by browser. Do a Google search on handling JavaScript/DOM events.

  3. #3
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It's not really determining which button was clicked that I'm having trouble with, it's the logic of setting up 1 button to increase the value of a variable and another to decrease it.

    I don't really understand how to attach the logic to buttons and have it effect a variable elsewhere on the page.

  4. #4
    We're from teh basements.
    Join Date
    Apr 2007
    Posts
    1,205
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It's just a simple matter of:

    if (button == 1) doSomething();
    else if (button == 2) doSomethingElse();
    else doYetAnotherThing();

  5. #5
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm fairly confident with attaching static logic to a button, but I'm trying to increase and decrease the same variable by 1 for 2 different buttons.

    for example, position =0;
    button 1 ++
    button 2 --

    I'm just unsuer of how to attach the ++ and -- to the buttons
    With what I've got so far I can make it work with a statid number, but I'm having trouble increasing the variable on clicks.

    If the position=0 and I press button 1 once, I want position to =1, if it's pressed again, it should = 2, then if the other button is pressed, it should decrease by 1 etc.

  6. #6
    We're from teh basements.
    Join Date
    Apr 2007
    Posts
    1,205
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I would create an object that keeps track of the current position and has methods for incrementing/decrementing it.

    Code:
    ImageGallery = function(imgElem) {
    
     this.element   = document.images[imgElem];
    
     this.images    = new Array();
                    
     this.position  = 0;
                    
     this.addImage  = function(imgUrl) {
                       this.images.push(imgUrl);
                      };
                    
     this.previous  = function() {
                       this.position = (this.position > 0) ? this.position - 1 : 0;
                       this.showImage();
                      };
                     
     this.next      = function() {
                       this.position = (this.position < (this.imageList.length - 1)) ? this.position + 1 : (this.images.length - 1);
                       this.showImage();
                      };
    
     this.showImage = function() {
                       this.element.src = this.images[this.position];
                      };               
                     
    };
    Then use it in your page:

    Code:
    <script type="text/javascript" src="ImageGallery.js"></script>
    <script type="text/javascript">
     var gallery;
    
     function init() {
      gallery = new ImageGallery('myImg');
      gallery.addImage('first_img.jpg');
      gallery.addImage('second_img.jpg');
      gallery.addImage('third_img.jpg');
      gallery.showImage();
     }
    
     document.body.onload = init;
    </script>
    <img name="myImg" alt="" />
    <button onclick="gallery.previous()">Previous</button>
    <button onclick="gallery.next()">Next</button>

  7. #7
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,
    I've tried to implement your code and nothing seems to be happening.

    If you could just show me how to make 2 buttons to just increase or decrease the value of position, that would be very helpful, as I'd then be able to do the bulk of it on my own (Which should help me grasp the concept, though it would take longer).

    Thanks.

    regards
    Steve

  8. #8
    Function Curry'er JimmyP's Avatar
    Join Date
    Aug 2007
    Location
    Brighton, UK
    Posts
    2,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code JavaScript:
    var imageList = ['a','b','c','d','e'];
    var position=0;
     
    document.getElementById('leftClick').onclick = function() {
        poistion = position === 0 ? 0 : position - 1;
    };
     
    document.getElementById('rightClick').onclick = function() {
        poistion = position === imageList.length ? imageList.length : position + 1;
    };
    James Padolsey
    末末末末末末末末末末末末末末末末末末末
    Awesome JavaScript Zoomer (demo here)
    'Ajaxy' - Ajax integration solution (demo here)

  9. #9
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I've just tested that code and I'm having trouble with it.
    I've tried adding an alert inside those functions and it's not appearing.

    I've corrected the spelling of position also and still nothing.

    I've even modified it so it's super simple and when alerted, it just gives 0

    What's wrong with this code?

    Code:
    var imageList = ['a','b','c','d','e'];
    var position=0;
     
    document.getElementById('leftClick').onclick = function() {
        position==-1
    	alert(position);
    };
     
    document.getElementById('rightClick').onclick = function() {
        position ==+1
    	alert(position);
    };

  10. #10
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Using double equals is where you are asking if the left side is equivalent to the right side.

    You'll be wanting to use += and -= instead.

    Code javascript:
    position += 1;

    Others use ++ instead (position++), but can easily lead to confusion when used with other terms, so it's a best practice to stay away from that notation and use += instead.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  11. #11
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That's still not having any effect
    here's the mark up:
    Code:
    <button id='leftClick' onclick="alert(position)">Previous</button>
    <button id='rightClick' onclick="alert(position)">Next</button>
    javascript
    Code:
    var imageList = ['a','b','c','d','e'];
    var position=0;
     
    document.getElementById('leftClick').onclick = function() {
        position += 1
    	alert(position);
    };
     
    document.getElementById('rightClick').onclick = function() {
        position -= 1
    	alert(position);
    };
    What's wrong with this code?

  12. #12
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Is what you're wanting to alert related to imageList? Because if so, you'll need to use imageList[position] to retrieve that part of the array.

    You'll also want to avoid increasing (or decreasing) past the end of the array, so you'll be wanting to use something like this instead:

    Code javascript:
    position = ((position + imageList.length) - 1) &#37; imageList.length;
    ...
    position = (position + 1) % imageList.length;
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  13. #13
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    All I want at the moment is help making 2 buttons or links that when pressed increases or decreases the value of "position" by 1.

    The rest I was going to experiment with.

    Eventually once I've got this working, yes I would like to relate the position to the image list items, but I'm fairly comfortable with that part.

    If anyone could show me some simple code for increase or decrease of a variable by button presses, I'd be very grateful.

  14. #14
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    position = position + 1;
    position += 1;
    position++;

    All of those are ways of increasing the variable. Use - instead to decrease the variable.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  15. #15
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's the code I have, it just alerts '0' all the time
    Code:
    var imageList = ['a','b','c','d','e'];
    var position=0;
     
    document.getElementById('leftClick').onclick = function() {
        position =position+1
    	alert(position);
    };
    What's wrong with the code above?

  16. #16
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    it's not able to make a permanent change to the position variable. There are a couple of ways to resolve that. One, you can store the position as a property of some common element, or two, you can remove the var keyword from the position variable and turn that it into a global variable.

    I should ask, are you wanting to do this the slow way and potentially come to understand things as we gradually work through them, or do you want to have the solution handed to you on a plate.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  17. #17
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think it's important that I understand this as we go through it.
    I don't want EVERYTHING handed to me, but I can't really progress until I get this increment thing sorted out.

    I've removed var, but it's still having no effect.

  18. #18
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by stevex33 View Post
    I've removed var, but it's still having no effect.
    Really? View the source code and double check, because it should.

    Here is some sample test code that demonstrates:

    Code html4strict:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>Test</title>
    </head>
    <body>
    <div id="leftClick">Left</div>
    <script type="text/javascript">
    var imageList = ['a','b','c','d','e'];
    position=0;
     
    document.getElementById('leftClick').onclick = function() {
        position =position + 1;
    	alert(position);
    };
    </script>
    </body>
    </html>
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  19. #19
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,147
    Mentioned
    16 Post(s)
    Tagged
    3 Thread(s)
    HTML Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    	<title>Untitled</title>
    	<meta name="generator" content="BBEdit 9.0">
    	<script type="text/javascript">
    	
    	window['onload'] = function() {
    	
    		var imageList = ['a','b','c','d','e'];
    		var position=0;
     
    		document.getElementById('leftClick').onclick = function() {
       		 	position++;
    			alert(position);
    		};	
    		
    		document.getElementById('rightClick').onclick = function() {
       		 	position--;
    			alert(position);
    		};
    	
    	}
    	
    	</script>
    </head>
    <body>
    
    
    <div id="leftClick" style="width:100px;height:100px;background-color:red;"></div>
    <div id="rightClick" style="width:100px;height:100px;background-color:blue;"></div>
    
    </body>
    </html>

  20. #20
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    The var keyword is still being used with the position variable. Remove the var keyword. This will make the position variable a global variable, and ensure that the onclick functions are able to correctly update that variable.

    The ongoing plan is to get started with a global variable, and then if there is an element that each event works with, we can use that replace the global variable with storing the value as a property of that common element.
    Last edited by paul_wilkins; Apr 14, 2009 at 00:38.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  21. #21
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    pmw57 I used your code and it works perfectly well for divs, so I modified the div label to "leftClick" and it seems to work fine.

    However it doesn't work with a button for some reason.
    ***Edit***
    I've just figured out why it wasn't working with buttons.
    Because the javascript was after the <td> but BEFORE the buttons, hence why it worked with 1 but not the other.

    I've given it a test and it seems to work well.

    So now when I do it, and I've got it set up, it should go through the list and change the image displayed.
    I've also added var back into the code and all seems fine.

    Sorry to put you through so much guys, I really appreciate the help.
    If I have trouble with this later once I'm all set up, I'll let you know, but all should be good now

  22. #22
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Right, okay, I've got it all set up, the only issue I'm having now is replacing the image.

    Here's the code that I've got:
    Code:
    <table width="500" border="0">
      <tr>
        <td id="TleftClick">Left</td>
        <td><img id="imageHere" src="images/copperfry.jpg"/>Image</td>
        <td><a id="TrightClick" href="#">Right</a></td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>Caption</td>
        <td>&nbsp;</td>
      </tr>
    </table>
    
    <button id='leftClick'>Previous</button>
    <button id='rightClick'>Next</button>
    <script type="text/javascript">
    /* <![CDATA[ */
    var imageList = ['copperfry.jpg','front.jpg','glasslid.jpg','greenfry.jpg','large.jpg','redfry.jpg','side.jpg','silverfry.jpg','small.jpg','withlid.jpg'];
    var imagePath = 'src="images\/'; 
    var position=0;
    var imageSrc = imagePath + imageList[position] + "\"";
    var imageListLength=imageList.length
    var imageHere = document.getElementById('imageHere');
    //imageHere.setAttribute("src",imageSrc);
    
    document.getElementById('leftClick').onclick = function() {
        if(position==0){
    	position=0;
    	imageSrc = imagePath + imageList[position] + "\"";
    	imageHere.setAttribute("src",imageSrc)
    	alert(imageSrc);
    	alert('list item ' + position + " " + imagePath + imageList[position])
    	}
    	else{
    	position =position-1
    	imageSrc = imagePath + imageList[position] + "\"";
    	imageHere.setAttribute("src",imageSrc)
    	alert(imageSrc);
    	alert('list item ' + position + " " + imagePath + imageList[position]);
    	}
    };
     
    document.getElementById('rightClick').onclick = function() {
        if(position==imageList.length-1){
    	position=imageList.length-1
    	imageSrc = imagePath + imageList[position] + "\"";
    	imageHere.setAttribute("src",imageSrc)
    	alert(imageSrc);
    	alert('list item ' + position + " " + imagePath + imageList[position]);
    	
    	}
    	else{
    	position = position+1
    	imageSrc = imagePath + imageList[position] + "\"";
    	imageHere.setAttribute("src",imageSrc)
    	alert(imageSrc);
    	alert('list item ' + position + " " + imagePath + imageList[position]);	
    	}
    	
    };
    
    /* ]]> */
    </script>
    As you can see, I've got it to alert out the correct item from the array, but the image itself isn't changing.
    I've also repeated code a few times, so if someone could advise on how I should go about minimizing that I'd appreciate it. I attempted a function earlier but it didn't go well.

    When I alert out imageSrc it shows the correct path to the image, so in theory it should change the src value to that new image.

    Can you see anything obviously wrong?

    I initially thought that it was because imageSrc was outside of the function, so I put it inside and it didn't change anything.

  23. #23
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,696
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    When you create the imageSrc, you do not include the parts outside of the quotes. By that I mean the src=" part, as well as the closing "

    This means the affected parts of code now become:
    Code javascript:
    var imageSrc = imagePath + imageList[position];
    ...
    imageSrc = imagePath + imageList[position];

    Cleaning up: We'll take the following code to work with. Semicolons have been added to the end of each statement, where they properly belong.

    Code javascript:
    if (position == 0) {
        position = 0;
        imageSrc = imagePath + imageList[position];
        imageHere.setAttribute("src", imageSrc);
        alert (imageSrc);
        alert ('list item ' + position + " " + imagePath + imageList[position]);
    } else {
        position = position - 1;
        imageSrc = imagePath + imageList[position];
        imageHere.setAttribute("src", imageSrc);
        alert (imageSrc);
        alert ('list item ' + position + " " + imagePath + imageList[position]);
    }

    Most of the statements in each condition are duplicates of each other, so we'll move them out of the condition itself.

    Code javascript:
    if (position == 0) {
        position = 0;
    } else {
        position = position - 1;
    }
    imageSrc = imagePath + imageList[position];
    imageHere.setAttribute("src", imageSrc);
    alert (imageSrc);
    alert ('list item ' + position + " " + imagePath + imageList[position]);

    Now the if statement can be reconsidered. It's only when the value is greater than 0 that we want to decrease it:

    Code javascript:
    if (position > 0) {
        position = position - 1;
    } else {
        position = 0;
    }
    imageSrc = imagePath + imageList[position];
    imageHere.setAttribute("src", imageSrc);
    alert (imageSrc);
    alert ('list item ' + position + " " + imagePath + imageList[position]);

    And that 5 line if statement can be performed by using the conditional operator:

    Code javascript:
    position = (position > 0) ? position - 1 : 0;
    imageSrc = imagePath + imageList[position];
    imageHere.setAttribute("src", imageSrc);
    alert (imageSrc);
    alert ('list item ' + position + " " + imagePath + imageList[position]);
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  24. #24
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You sir, are a genius

    I removed src=" and the closing " like you suggested, and without further modification, it works as it's supposed to.

    I've attempted to implement the if statement as suggested:
    position = (position > 0) ? position - 1 : 0;

    But for when I want to make sure that it doesn't excees the last item in the array I get a bit stuck.

    I attempted :
    position = (position <= imageList.length) ? position + 1 : (imageList.length)-1;

    But it allows me to go to iem 10 which is undefined, and item 11, also undefined, before on the 3rd click, going back to item 9.
    The person viewing the image gallery(once the alerts are removed) wont notice the difference, but I'd like to understand this and correct it.

    I maye leave it as:

    if(position==0){
    position=0;
    }
    else{
    position =position-1;
    }

    and

    if(position==imageList.length-1){
    position=imageList.length-1;
    }
    else{
    position = position+1;
    }

    as it's easier to read, but I would like to learn your method and why the way I'm attempting to implement it isn't working.

  25. #25
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    328
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    anyone available to enlighten me?


Bookmarks

Posting Permissions

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