Sep 18, 2013

Changing Site Logo URL with Client Side Script

In SharePoint, the site logo URL is set in the master page as the NavigateUrl  attribute for the SPLinkButton control, usually with the value of either ~site or ~sitecollection, e.g:
<SharePoint:SPLinkButton runat="server" NavigateUrl="~sitecollection/">

Most of the time this either is what we want, or can be changed in a custom master. 

Lately, though, I have been working on a project where the company intranet is split in two: there is one instance for general intranet, and another one for a special purpose. Both instaces use the same master pages, and the only UI customizations I have been making for the special site collection (in its own web app, not that it matters) are some special page layouts and CSS files - and a bit of JavaScript.

The incentive is to integrate the special site collection to the general intranet as seamlessly as possible, i.e. in a way that the average user wouldn't need to even notice that they actually navigate from one site collection to another and back. One task was to add an intranet root node to the breadcrumb trail, which did not cause too big of a headache, but the other task, changing the URL for the site logo link was not as straight forward as one would have expected.

The problem was created by the SharePoint control adding (invisible) empty text nodes inside the parent div. So while the <a> element seemed to be the firstChild of the div, this was not actually correct. Inspecting the dom tree of the div in Chrome dev console, I found this:

firstChild was trying to change attribute for the text node [0] and childNodes[1] returned empty object for whatever reason, so finally, the problem was solved rather simply by using children[0]:

window.onload = function setLogoUrl() {
    var logolink = document.getElementById('DeltaSiteLogo').children[0];
    logolink.setAttribute('href', 'http://intranet.mothership');

No comments: