MyBB Community Forums
Avatar in Header with Fallback - Printable Version

+- MyBB Community Forums (https://community.mybb.com)
+-- Forum: Resources (https://community.mybb.com/forum-8.html)
+--- Forum: Tutorials (https://community.mybb.com/forum-38.html)
+--- Thread: Avatar in Header with Fallback (/thread-149518.html)



Avatar in Header with Fallback - effone - 2014-01-01

Dependency:
jQuery library with proper noConflict(); included.

Background:
As requested by a member of the community in this thread:
http://community.mybb.com/thread-149474.html
I've made this simple jQuery function.

Purpose:
As we all know that this variable: {$mybb->user['avatar']} returns the avatar url path of the logged in user, so using this variable we can display logged in user's avatar in welcomeblock. But there is a problem. If the user doesn't have set any avatar; this variable returns a blank value; thus the avatar area remains with an empty spaceholder.

The idea is to display the avatar of the current user, if set, else a predefined default avatar.

Process:
In header_welcomeblock_member template add an image tag where you wanna show the avatar.
<img id="avatar"/>

Upload the default avatar image, say it is:
{$theme['imgdir']}/defaultavatar.png

Now add this script at the end of header_welcomeblock_member template:
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function(){
var user_avatar = "{$mybb->user['avatar']}";
var default_avatar = "{$theme['imgdir']}/defaultavatar.png";
jQuery( "#avatar" ).error(function() {
  jQuery(this).attr( "src", default_avatar );
}).attr( "src", user_avatar );
});
</script>

Things to make sure
1. Ensure that the path of the default avatar image you are linking via variable 'default_avatar' is correct.
2. Remember to include jQuery library in headerinclude template if it is not already ...

Happy coding.