jQuery Image Replacement not working

Hello,

I have a big image and several small thumbnails. Every time the user clicks on one of the thumbs, I want the big image to update. This is my code:

$("#thumbs a").click(function() {
		var largePath = $(this).attr("href");
		$("#largeImg").attr(src: largePath);
		return false;
	});

And the HTML:

<ul id="thumbs">
	<li><a href="images/01.jpg"><img src="images/thumbs/01.jpg" /></a></li>
	<li><a href="images/01.jpg"><img src="images/thumbs/02.jpg" /></a></li>
	<li><a href="images/01.jpg"><img src="images/thumbs/03.jpg" /></a></li>
</ul>
<div>
	<img id="largeImg" src="" />
</div>

Although, the thumb image gets always displayed in an empty window, as if there is no “return false”. If I click Back in the browser, I see that the big image has been indeed changed just before the link executed. Why is my “return false” not firing and preventing the browser from following the link?

That happens when the links don’t have the click event attached to them. Why would that happen? It happens when you attempt to add a click event when no body content yet exists.

If that is the cause, you need to place your jQuery code in a callback, so that jQuery can then execute your code after the body content becomes available.


$(function () {
    // your jQuery code in here
});

If it’s not due to that, then we’ll need to see a test page that demonstrates the problem, so that the fuller context can be examined in which to find the actual cause.

Thank you for your reply!

I have put the JS in the document.ready event like this:

$(document).ready(function() {
	
	$.fn.preload = function() {
	    this.each(function(){
	        $('<img/>')[0].src = this;
	    });
	}
	
	var imgSwap = [];
	$(".for_preload").each(function() {
		imgUrl = this.href;
		imgSwap.push(imgUrl);
	});
	$(imgSwap).preload();
	
	$("#viewImage_thumbs a").click(function() {
		var largePath = $(this).attr("href");
		var largeAlt = $(this).attr("title");
		$("#largeImg").attr({ src: largePath, alt: largeAlt });

		if ($(this).css("border-top-width") == "0px") {
			$("#viewImage_thumbs a").animate({borderTop: "0"}, 160);
			$(this).animate({borderTop: "5px solid #fac400"}, 400);
		}
		return false;
	});
})

Is this what you mean by callback?

Patrick

Yes, that’s right.

Have you tried jQuery’s preventDefault method, instead of return false?

If that doesn’t help, there might be something elsewhere helping to cause the problem.
A test page that demonstrates the problem will help us to trace the issue down to its root cause.