Skip to content

Instantly share code, notes, and snippets.

@natewinck
Created August 15, 2014 13:06
Show Gist options
  • Save natewinck/7b2d1698dd0ad8288bfb to your computer and use it in GitHub Desktop.
Save natewinck/7b2d1698dd0ad8288bfb to your computer and use it in GitHub Desktop.
// Create a link out of any element while maintaining
// the ability to open those links in a new window/tab/etc.
$("body").on("click", "[data-href]", function(e) {
// Create the anchor based on the data-href attribute
$anchor = $("<a>").attr("href", $(this).attr("data-href"));
$anchor.css("display", "none");
// Check to see if the user is holding a modifier key
if (e.ctrlKey || e.shiftKey || e.metaKey) {
$anchor.attr("target", "_blank");
}
// Add the anchor to the end of the document
$("body").append($anchor);
// Simulate a click
$anchor[0].click();
// Remove the anchor from the document
$anchor.remove();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment