Monday, November 4, 2013

Programmatically call a Javascript function from an anchor tag's onclick event

While doing some work on a custom, navigation-like control on one of my SharePoint 2013 sites, I ran into a situation in which I needed to override the functionality of an anchor tag (i.e. <A>) so that it would call a javascript method and pass the URL as a parameter as opposed to simply directing the user to the referenced web page when the user clicks on it. In case you're curious, I need to do this because I'm going to display the dashboard/report that I'm referencing in a DIV tag as opposed to directing the user to the actual dashboard/report.  The following code sample provides a somewhat simplified example of what I did so that I can convey the concept without getting bogged down in too much detail (I included some of the Tableau dashboard code as a bit of a bonus as well as convey what I was up to with this):


<div id='menu'>
    <a href='http://UrlOfTableauReport1'></a>
    <a href='http://UrlOfTableauReport2'></a>
    ...
</div>

<div id='dashboard'></div>

<script>
     // Override the onlick so that it builds the dashboard in the DIV as opposed to redirecting the user to the dashboard's page

     jQuery( 'div a' ).click(function() {
          renderDashboard( this.href );
          return false;
     });

     // Construct the HTML associated with the Tableau dashboard that I'm going to display in a DIV tag 
     function renderDashboard(url) {
 var dashboardHTML = "<iframe width='700px' height='500px' class='tableauViz' src='" + url + "?:embed=y&amp;:host_url=https%3A%2F%2FTableauServerHostUrl%2F&amp;:tabs=no&amp;:toolbar=yes&amp;:allowscriptaccess=always&amp;:loadOrderID=5' frameborder='0' marginwidth='0' marginheight='0' allowtransparency='allowtransparency' style='border-bottom: medium none; border-left: medium none; padding-bottom: 0px; margin: 0px; padding-left: 0px; width: 700px; padding-right: 0px; display: block; height: 500px; border-top: medium none; border-right: medium none; padding-top: 0px'></iframe>";
 document.getElementById("renderDashboard").innerHTML = dashboardHTML;
     }
</script>