Skip to main content

Cloud

Create Dynamic Nav Images for SharePoint with jQuery

Content management systems are great for automation. SharePoint will keep your navigation updated as you add or delete sub-sites and pages. This is helpful but it can limit the ability to customize the UI. If you were writing the HTML code from scratch you could specify different CSS classes for each and display a different background image. However when the nav is created by SharePoint there is nothing unique about each of the elements so an attempt to add a specific background image to one, via CSS, adds the same background to all.
For this demo we will use jQuery to find the text of each link in the navigation and give it a background image with a file name that matches that text. That way all an admin has to do to add an item to the nav in SharePoint is create a sub-site, and then upload an image to the images folder.
screen View Demo | labView Code
The HTML. For the sake if demonstration we will say that this is the HTML created by the CMS after an admin has created a HOME page and four sub-sites.

<a href=”/Home” >Home</a>
<a href=”/News” >News</a>
<a href=”/Events” >Events</a>
<a href=”/Store” >Store</a>
<a href=”/Support” >Support</a>

The CSS. In CSS, we prepare the anchor for the backgrounds with properties.

a {
background-repeat:no-repeat; /* Do not repeat the background image */
display:block; /* Make the anchor a block element */
float:left; /* Make the block elements inline horizontally */
height:36px; /* Make the anchor the height of the image */
width:102px; /* Make the anchor the width of the image */
}

The jQuery. This function will find each anchor and add a background image with the same file name as the text of the item.

$(‘a’).each(function() {
var $this = $(this); // Since we will use the selector more than once we make it a variable
$this.css({‘background-image’:’url(https://blogs.pointbridge.com/Blogs/broweleit_seth/Lists/Photos/ + $this.text() + ‘.gif)’,’text-indent’:’-9999px’});
});

Notice. We hide the text with the TEXT-INDENT property in the jQuery, and not in the CSS, so that browsers with JavaScript turned off will still the nav items. Also, the nav is still usable if a user has the CSS disabled.
With this code in place, a SharePoint admin can simply add a new sub-site, and an image with the same file name, and have a UI that is as attractive as any site out there.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Seth Broweleit

More from this Author

Follow Us