[Drupal] How to stay on the current page and location when clicking on a link that is associated with a javascript function

| | 2 min read

In one of my drupal projects, I had a requirement to open some search result page in a new tab. I had given '#' as a place holder for the href attribute of the search link that needs to execute a javascript function on click to open the search result page on new tabs. I have added necessary code on the click event of this link to open the search results in new tabs and it was working properly. But when I click on this search link the current tab will go to the top of the page, since the '#' attribute will redirect to the top of the page.

If the page height is too large and the user was reading at the bottom of the page, it makes difficulty for the user to scroll back down to read the rest part of the page. My requirement was to stay on the same location. I have solved this issue by using the following code in my js file.

Suppose that the id of the link is 'search-link', then add the following code in your js file.

      return false; //My code to execute on click

The return value of an event handler determines whether or not the default browser behaviour should take place as well. So by returning false in the above function will allow you to stay on the same location when clicking on that link. This can also be achieved by using event.preventDefault(). This will also prevent the default browser behaviour of that event. So instead of return false, you can also use event.preventDefault() inside the click function.