Friday, January 11, 2013

Rails - opening a new browser tab or window in the foreground

In a Rails website, suppose you'd like to open a new window (or new tab, depending on the user's browser settings) when the user clicks a link. And suppose you'd like to make sure the new tab or window comes to the foreground. And suppose you'd like to specify the URL the "Rails way," using link_to rather than hard-coding an HTML a tag. Here's how...

This example assumes "merchant" is an instance of a Rails model class with RESTful routes. It creates a "Shop now" link that opens the merchant's page in a new tab or window and gives it the focus. Of course, this relies on JavaScript's being enabled in the user's browser.

<%= link_to "Shop now", merchant, onclick: "var w = window.open(this.href); w.focus(); return false;" %>

1 comment: