0

I've got a simple function that can either return a match found or no match found result.

If no match is found I want it to display a generic "no user found" image. The below code works fine, but I want to do this the right way. This link

Show/hide image with JavaScript

seems to discuss a far more complex way of achieving what I'm doing.

But is my method incorrect?

JS

success: function (friendMatches) {
            if (friendMatches.length === 0)
                console.log('NO MATCH FOUND!!!');
        $(".no_user").show();
            else // Query executed with success
                console.log('MATCH FOUND!!!');
        },

HTML

<img style="display:none" src="/img/no-user.png" class ="no_user" alt="No user found">  
Community
  • 1
  • 1
Dano007
  • 1,872
  • 6
  • 29
  • 63
  • 1
    I see nothing wrong with your code, other than it's confusing to read without { } around your `if` statement – mituw16 May 14 '14 at 14:21

1 Answers1

1

How about this:

JS:

success: function (friendMatches) {
            var src;
            if (friendMatches.length === 0) {
                src = 'no-user';
                alt = 'No user found';
            } else { // Query executed with success
                src = userFilename; //Put in the correct filename
                alt = userName; // Put in the correct username
            }
                $(".userImage").attr('src', '/img/' + src '.png');
                $(".userImage").attr('alt', alt);
        },

HTML:

<img class="userImage" src="" alt="" />  

This way, you don't need an unused object in the dom.

nils
  • 25,734
  • 5
  • 70
  • 79