Reputation: 1792
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 :)
Upvotes: 1
Views: 743
Reputation: 630627
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:
<a>
, it has the hashthis
since this
refers to the <a>
element<ul>
doesn't have a id="ul"
attribute, so the selector should be ul
, not #ul
.load()
which is for fetching content, instead set the src
if the <img>
using .attr()
.Upvotes: 2