When you develop a web page with JQuery and Javascript, you probably have several places on the page where you have to connect javascript function links to text or images. Suppose you have a simple javascript function defined:
function open_data(event) {
alert("Open data tab");
}
And now you would like this function open_data (which will show/hide some div or something in this direction) to trigger when you click on a link. You could do something like this:
Open Data
When you click on this link, the function open_data is called. This is all good. However, when you mouse-over the "Open Data" text, you will see the link displayed as "javascript:open_data(event)". However, what about opening the data in a new window or sending the link to the data to someone via URL?
However, when you click on the example library link inside the expressRNA webapp, this does not redirect the browser to the new URL. This would be too heavy. Instead, a javascript function is triggered, which directly shows you the data without reloading the web page (hides some div elements and loads content into the library div element). At the same time, you can right-click on the example library link and "Open in new tab" in the browser or Command-Click on Mac/Windows to open in new tab. This then opens a new window, and reloads the whole expressRNA webapp with the correct data displayed (example library).
How do you achieve the behaviour where command-clicking on a link opens the link URL (href) and simply clicking on a link runs a javascript function?
The first idea is to do something like this:
Open Data
This works great. If you click on the link, the javascript function "open_data" is run. If you right-click and "Open in new tab", the URL "expressRNA.org/data" is open in a new tab. However, if you command-click the link, the thingy doesn't work as expected.
You need a little bit more logic in the open_data function to catch the command-click events to make it really really nice for the user.
function open_data(event, url) {
if (event.ctrlKey || event.metaKey) {
window.open(url);
} else {
alert("Open data tab");
}
}
And voila. You now have links on your web page that trigger a javascript function when you click them. Still, you can attach a URL to the link (href), where if you "Open in new tab" or command-click the link, a new browser tab is open and the URL is loaded. This is super essential for web apps sharing data, since you would like, for example, to open several analysis and libraries (expressRNA) in different browser tabs, which you would also like to share with colleagues via the URL links.
Thanks for reading! and if it was helpful for you, leave a comment below.