0

I have a section of a page (widget) which I would like to use as a link (clicking anywhere will go to a different page):

<!-- just an example. real application is quite a bit more complex -->
<div data-href="/page">
   <h1><a href="/page">Title of sample content</a></h1>
   <p>
        some content here with an image
        <img src="image.jpg">
   </p>
   <div>
        and many more elements in here
        <div>
             with nested structure with semantic meaning
        </div>
   </div>
</div>

Since the section is <div>, I cant wrap it around <a> since that is against HTML spec. I also cant change the divs to span since they actually have semantic meaning.

Currently I attach a JS click event on which I change the browser location which effectively works as a link:

$('div').click(function() {
    window.location=$(this).data("href");
});

This works ok except when you Ctrl+Click or Cmd+Click on the <a> to open the link in the new tab. Since for this you are not explicitly doing right click, the browser registers it as a click hence the function gets executed anyway.

I guess I could check if any modifier key is pressed at the click event however I feel that is a bit cumbersome. Is there a nice JS solution for this?

miki725
  • 27,207
  • 17
  • 105
  • 121

1 Answers1

0

You can do something like this (jQuery for the click handler):

$(selector).click(function(e) {
  if(e.shiftKey) {
    //Shift-Click
  }
  if(e.ctrlKey) {
    //Ctrl+Click
  }
  if(e.altKey) {
    //Alt+Click
  }
});

You can handle whichever you want inside an if inside the click handler like shown above

Bhavik
  • 92
  • 2
  • 5
  • 12
  • thx of your suggestion however as per my question, I would prefer not to rely on checking for modifier keys – miki725 Jul 05 '14 at 14:16