Question

I'm using a forum software where you can pull up an avatar link using this: {$mybb->user['avatar']}

If no avatar is set then nothing is returned. I want to show an image if no avatar is set.

Currently the HTML is setup like this:

    <div id="avatar"><div style="background: url({$mybb->user['avatar']}) center center no-repeat;"></div></div>

The outer div is empty and in the background. This one is the one I'm adding a class too (.defaultavatar) so that a default avatar will display.

The inner div is the one with the avatar displaying. If no avatar is uploaded/selected then it will appear blank.

This is the javascript I'm using:

    var myavatar = {$mybb->user['avatar']};

    if(typeof(myavatar) = null){ 
        jQuery('#avatar').addClass('defaultavatar');
    }

If the avatar URL is empty I want the class defaultavatar to be added to the first div.

How can I do this (get it to work)?

Thanks very much, Jack Clarke

Was it helpful?

Solution

There are two meanings for undefined in javascript. I'm not sure what their exact names are, for my example I will call them undefined and REALLY undefined.

The regular undefined is what you get when you try to get a value from something that has been declared but not initialized. In other words, the interpreter knows the thing you're talking about, but that thing has no value yet.

You can use a simple if statement to cast your variable to a boolean to check if it is this type of undefined. Be aware that this cast will also cast empty strings '' and numeric 0 to false as well. If you need to consider empty strings and numeric 0 as well, use myDeclaredVariable === undefined for the condition instead.

if (myDeclaredVariable) {
    // myDeclaredVariable is initialized with a "truthy" value
} else {
    // myDeclaredVariable is either uninitialized or has a "falsey" value
}

The REALLY undefined is what you get when you try to access a random variable without ever even declaring it. The interpreter has no idea what you are talking about and it will throw a javascript exception if you try to do anything with it. To handle this situation, you need to use the typeof operator.

if (typeof myPossiblyDeclaredVariable !== 'undefined') {
    // myPossiblyDeclaredVariable has been declared
} else {
    // myPossiblyDeclaredVariable has not been declared yet
}

You can see a related StackOverflow question here.

OTHER TIPS

in your if condition, the syntax has a problem. Single equal is assignment.

at least change this

if(typeof(myavatar) = null)   

to

if (typeof myavatar == 'undefined')

Depending on what {$mybb->user['avatar'] returns, it may be sufficient to do:

if (myavatar) {
  // do stuff
}  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top