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 🙂
You can write your code a bit shorter like this:
You can try it out here, a few changes from your original:
<a>, it has the hashthissincethisrefers to the<a>element<ul>doesn’t have aid="ul"attribute, so the selector should beul, not#ul.load()which is for fetching content, instead set thesrcif the<img>using.attr().