1

I have two div's which I would like to be clickable. Each div has an anchor link within which I would like to use for each div's link.

I'm using the help below which works for the left div but not the right. http://css-tricks.com/snippets/jquery/make-entire-div-clickable

Not quite sure what I'm missing or if there is a better way to do this? Ideally I would like to use just CSS but this option would still work even if js is disabled.

Any help would be great.

$('.left').click(function(){
     window.location=$(this).find("a").attr("href");
     return false;
});
$('.right').click(function(){
     window.location=$(this).find("a").attr("href");
     return false;
});


    <div class="left">
    <div class="left-content">
        <h2><a href="#">title</a></h2>

        <ul>
            <li>Link</li>
            <li>Link</li>
            <li>Link</li>
        </ul>
    </div>   
</div>

<div class="right">
    <div class="right-content">
        <h2><a href="#">title</a></h2>

        <ul>
            <li>Link</li>
            <li>Link</li>
            <li>Link</li>
        </ul>
    </div>        
</div> 
Jemes
  • 407
  • 1
  • 9
  • 27

4 Answers4

5

Putting DIVs inside of anchors is valid in HTML5 and is backwards compatible with other DOCTYPES.

<a href="#">
    <div class="right">
        <div class="right-content">
            <h2>title</h2>
            <ul>
                <li>Link</li>
                <li>Link</li>
                <li>Link</li>
            </ul>
        </div>        
    </div> 
</a>
Matthew Darnell
  • 4,300
  • 2
  • 17
  • 29
  • Thanks thats looks like a nice solution didn't know you could wrap anchors around div's. As long as it validates looks like the best option rather than js. – Jemes Mar 13 '12 at 21:34
2

Use it this way:

$('.left').click(function(){
     window.location=$(this).children("a:first").attr("href");
     return false;
});
$('.right').click(function(){
     window.location=$(this).children("a:first").attr("href");
     return false;
});
Sven Bieder
  • 5,081
  • 2
  • 18
  • 27
1

works fine here

$(document).on('click','.clickable', function(){
    window.location=$(this).find("a").attr("href");
    return false;

});

the only thing that I've added is pointer on hover.

Alex Okrushko
  • 5,730
  • 5
  • 38
  • 57
0

You can do this with CSS. Give your anchor tags display: block;. Then put ul inside the a.

Here is a live demo. If you hover over either div, you'll see that they are both clickable.

Colin Kenney
  • 587
  • 5
  • 10