Wednesday, May 23, 2012

Click Event with fadeToggle() - what is wrong with my code?

I created an interactive map of London using the <map> tag which has 15 <area> tags defined. Upon clicking on any of the 15 areas, the source of the map is replaced by another, according to the area which was clicked on. All the areas have an individual id and the source changes according to that id.



Clicking again on the area reverts the map image back to its original source.



The simplified HTML for this is a bit like so:



<IMG id="londonmap" SRC="images/londonmap.png" USEMAP="#london">
<map name="london">
<area id="dalston" href="#" shape="rect" coords="364,75,500,200"
alt="Dalston Tube Stop" title="Dalston Area">
</map>


The jQuery I used for clicking and unclicking looks as follows:



$(document).ready(function()
{
$('#dalston').click(function()
{
// select the image and determine what the next src will be
var londonMap = $('#londonmap');
var newImageSrc = londonMap.attr('src') != 'images/dalstonmap.png' ? 'images/dalstonmap.png' : 'images/londonmap.png';

// re-bind the src attribute
londonMap.attr('src', newImageSrc);
});
});


Everything up to here works just fine. Now, I thought it would be nice, for just a bit of an extra effect to have the changing images .fadeToggle() when clicked for a smoother transition and as such changed to code to this:



$(document).ready(function()
{
$('#dalston').click(function() {
$('#londonmap').fadeToggle('slow', function()
{
// select the image and determine what the next src will be
var londonMap = $('#londonmap');
var newImageSrc = londonMap.attr('src') != 'images/dalstonmap.png' ? 'images/dalstonmap.png' : 'images/londonmap.png';

// re-bind the src attribute
londonMap.attr('src', newImageSrc);
});
});
});


The problem now is that only half the code reacts as I expected - the original image fades out, but the second one never takes its place. I'm guessing it has something to do with the order in which the events happen, but being a bit of a noob in jQuery I can't really tell what's going wrong.



Any help would be much appreciated as this is the last thing stopping me from finishing the map!





No comments:

Post a Comment