Search code examples
javascriptjqueryhtmlsrcattr

Javascript attr change with fade issue


I'm trying to have a small gallery. 1 large image with 3 underneath. When one of the images underneath is clicked, it will change the img src of the main/large image with a fade animation.

the html is -

    <div class="col-xs-12 col-sm-6">
        <div class="col-xs-12">
            <div class="col-xs-12 col-sm-12" style="padding-left: 5px; padding-right: 5px;">
                <img alt="Bentley Flying Spur" id="main1" src="img/gallery/flying-spur/1.JPG" style="border-bottom: 10px solid #fff;" width="100%" />
            </div>
            <div class="col-xs-4 col-sm-4" style="padding-left: 5px; padding-right: 5px;">
                <a class="altimage1" href="" title="switch"><img alt="" src="img/gallery/flying-spur/1.JPG" width="100%" /></a>
            </div>
            <div class="col-xs-4 col-sm-4" style="padding-left: 5px; padding-right: 5px;">
                <a class="altimage2" href="" title="switch"><img alt="" src="img/gallery/flying-spur/2.JPG" width="100%" /></a>
            </div>
            <div class="col-xs-4 col-sm-4" style="padding-left: 5px; padding-right: 5px;">
                <a class="altimage3" href="" title="switch"><img alt="" src="img/gallery/flying-spur/3.JPG" width="100%" /></a>
            </div>
        </div>
        <h2>
            Flying Spur W12
        </h2>
        <p>
            Colour | <strong>Sapphire Blue</strong>
        </p>
        <p>
            Engine | <strong>6.0 litre twin-turbocharged W12</strong>
        </p>
        <p>
            Max Power | <strong>616 bhp / 460kW / 625 PS @ 6,000RPM</strong>
        </p>
        <p>
            Top Speed | <strong>199mph / 320km/h</strong>
        </p>
    </div>

and the javascript that works without the fade is....

    $(function () {
    $('.altimage1').click(function () {
        $("#main1").attr('src', "img/gallery/flying-spur/1.JPG");
        return false;
    });
});

and the javascript I tried for the fade is

$('.altimage12').click(function () {
    $("#main4").fadeOut(400);
    $("#main4").attr('src', "img/gallery/1951/3.JPG");
    $("#main4").fadeIn(400);
    return false;
});

But this just refreshes the page. Any insight would be greatly appreciated


Solution

  • I fixed your code, and this is how it is:

    $('[class*="altimage"]').click(function() {
      var elem = $(this);
      $("#main1").fadeOut(400, function() {
        $("#main1").attr('src', elem.find("img").attr('src')).fadeIn(400);
      });
      return false;
    });
    

    Here is the JSFiddle demo

    Please note that the pictures are different since they are randomly generated in the demo.