jstacks
jstacks

Reputation: 2437

Clickable div with nested divs inside

I am looking to make a clickable div that has further divs nested inside. From what I understand, if you style an anchor tag display:block, it acts as a block (div) and you can nest the div you want clickable within it.

However, I don't believe you can continue nesting further divs beyond that... if this is the case, why is that?

And also, what would be the best/simplest solution to solve this. It would ideally be all CSS/HTML, but a jQuery solution be okay if CSS/HTML truly aren't possible.

Anyway... example:

This would work (yes?) as long as the anchor is styled display:block...

enter code here

<a>
     <div id='first'>
     </div>
</a>

This would not...

enter code here

<a>
     <div id='first'>
          <div id='inside first'>
          </div>
          <div id='inside first 2'>
          </div>
     </div>
</a>

Any and all help appreciated. Thanks!

Upvotes: 0

Views: 2434

Answers (4)

Aerendel
Aerendel

Reputation: 615

Putting div tags inside an anchor tag is not valid html so you shouldn't be doing that. In your case, the easiest would be to use a little JavasScript and define a simple onclick event on your parent div such as:

 <div id='first' onclick="javascript:MyRedirectFunction()">
      <div id='inside first'>
      </div>
      <div id='inside first 2'>
      </div>
 </div>

Then if you want the user to understand that this div will be clickable, you can use CSS to give it an anchor-like behavior such as:

div#first{ cursor: pointer; }
div#first:hover{ background-color:#CCCCCC;}

Upvotes: 0

Ram
Ram

Reputation: 144659

if you are using HTML5 Doctype it's valid to use anchor tags for wrapping div elements, supposing you are not using HTML5 Doctype you can also try this:

div#first {
  cursor: pointer;
}

$('#first').click(function() {
    window.location = 'http://www.example.com'
})

Upvotes: 1

Zoltan Toth
Zoltan Toth

Reputation: 47667

Sure your second variant will work - http://jsfiddle.net/W5jG8/ You can go even deeper. In fact there is no limit how deep you can go with nesting. (Or maybe there is but it's not relevant to real life cases)

But it's semantically incorrect to nest block level elements into originally inline ones before HTML5. One solution is to replace all <div>-s with <span>-s and also make them block.

Or you can use <div>-s with jQuery and attach a click listener to the wrapper - http://jsfiddle.net/W5jG8/

Upvotes: 1

epsilones
epsilones

Reputation: 11609

The simplest way is to use jquery, to specify an Id for the div you want to make clikable like so :

$('#div_Id').click(function(){

blablabla...

});

Here's somme doc : http://api.jquery.com/click/

Upvotes: 0

Related Questions