views:

30

answers:

1

Hey guys :)

I've a ul li menu such like:

<ul>
     <li><a href="#1">Image #1</a></li>
     <li><a href="#2">Image #2</a></li>
     <li><a href="#3">Image #3</a></li>
     <li><a href="#4">Image #4</a></li>
</ul>

And I have a container with an image like:

<div id="image-container">
     <img src="images/1.jpg">
</div>

I want to switch the image in "image-container" div using "hash" and "load" (every image is in /image/ folder and each is named like hashes, so loads images/2.jpg etc.

I'm trying this way:

$("#ul li:nth-child(1)").click(function(e) { 
        e.preventDefault();   
        var hash = this.parentNode.hash;  
        $("#image-container").load('images/'+ hash.substring(1) +'.jpg');

$("#ul li:nth-child(2)").click(function(e) { 
        e.preventDefault();   
        var hash = this.parentNode.hash;  
        $("#image-container").load('images/'+ hash.substring(1) +'.jpg');

$("#ul li:nth-child(3)").click(function(e) { 
        e.preventDefault();   
        var hash = this.parentNode.hash;  
        $("#image-container").load('images/'+ hash.substring(1) +'.jpg');

(...)

But it doesn't work so well (I guess I'm going to need something slightly different than load, because it won't change my image anyways?).

Thanks a lot.

And by the way - is there a way to write my jQuery code shorter (in one function, because now I have multiple with the same body)?

Thanks a lot, Ada :)

+2  A: 

You can write your code a bit shorter like this:

$("ul li a").click(function(e) { 
  e.preventDefault();   
  $("#image-container img").attr('src', 'images/'+ this.hash.substring(1) +'.jpg');
});

You can try it out here, a few changes from your original:

  • Attach the handler to the <a>, it has the hash
  • You can bind the same handler to many elements, just use a selector that grabs all the element you want
  • Get the has from this since this refers to the <a> element
  • You <ul> doesn't have a id="ul" attribute, so the selector should be ul, not #ul
  • Don't use .load() which is for fetching content, instead set the src if the <img> using .attr().
Nick Craver
+1 for the free code review...
cinqoTimo