Search code examples
javascriptimagefadeinif-statementsrc

Javascript If/Else statement change img src


I've got a drop functioning dynamic drop down menu that I'd like to add a little more functionality to. The menu is the page navigation and hovering over a link changes the source of an image in the content area, reflecting the active link. It's a simple attr(src) change.

I've added some code to fade the active image out, change the source back to the default, and fade it and back in upon leaving the menu, but would like to frame that code within an If/Else statement; preventing the image from fading out and back in if it's source is unchanged from the default.

The syntax seems correct, but the function is not working correctly. I'm relatively new and am likely missing something. I'd greatly appreciate any advice for functional, more reliable code!

Thank you for your time, Daniel


The function embedded within the else statement (fade out, change source, fade in) works as I'd like it to.

$("#trigger").mouseleave(function(){
    var img = $("#img_home");
    if (img.src = "Images/IMG_4663_bw.jpg"){
      img.noop();
    } else {
      img.fadeOut(1000, function(){
         img.attr("src","Images/IMG_4663_bw.jpg");
         img.fadeIn(1000);
      });
    }
});

Solution

  • if (img.src = "Images/IMG_4663_bw.jpg")
    

    You're assinging the value, you need the == operator, not the = operator.
    If you're only looking for the else condition though, just inverse the condition:

    if (img.attr('src') != "Images/IMG_4663_bw.jpg") {
        // fade and stuff
    }