Example: Providing Support for HTML Anchor Tags Within Expandable Content Areas
You can place named ‘anchor’ tags in HTML. If the URL used to access your website specifies a named anchor, the webpage will open and automatically scroll to the location of the anchor in the document.
However, on many websites you cannot rely on this anchor functionality if the anchor is situated within an expandable content area. Because expandable content areas usually default to closed, the anchor is not visible on the screen when the page is loaded. Because the anchor isn’t visible, the browser doesn’t automatically move to the anchor. Moreover, there is not an automatic mechanism to open the relevant expandable area.
Link showing default functionality: https://drupaltraining.gmu.edu/anchors-expandables-original#anchor2
The logic of this script is as follows:
- The script checks for the presence of a named anchor in the URL.
- If an anchor is found in the URL, the script checks for a corresponding named anchor within the web page.
- If a corresponding named anchor is found within the web page, the script identifies and opens the expandable content area containing the anchor, if any.
- The script then scrolls to the location of the anchor (minus a few pixels to account for the menu bar).
Link to working example: https://drupaltraining.gmu.edu/anchors-expandables#anchor2
// What: Provides functionality for cases where a named anchor is situated within an expandable content area.
// Who: Jan Macario
// When: 20180214
// if there is a hash/anchor included in the URL...
// check to see if there is a corresponding anchor in the page, and...
// if the anchor is within an expandable content area, open that content area, and...
// scroll the viewport to that area...
// plus 100 pixels to account for the height of the header menu.
//is there a hash in the URL?
//Get hash value
//Get anchor element, if any
$anchor = jQuery("a[name='" + anchor_name + "']")
//Get parent expandable content area, if any
$container = $anchor.parents("div.expanded-content");
//Expand parent expended-content div, if any
//Scroll viewport to anchor
- Script to mitigate the fact the regular anchors (not within expandable areas) end-up hidden behind the menu bar on the Mason core website.
- Script to change page design (e.g. color-coding) where desirable.