开发者

Make a whole div clickable

I have a link inside a div and I need to make the whole div clickable... found several tutorials on开发者_运维知识库 the Internet but non of them worked for me...


Raw JavaScript:

<div onclick="alert('You clicked me !')">Click Me</div>

jQuery:

$('#div_id').click(function(){
  alert('Clicked !!');
});

Update: (With reference to your link)

<div class="myBox">
     blah blah blah.
    <a href="http://google.com">link</a>
</div>

jQuery:

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

The above code cancels the default action of link (going to link) with return false and binds the click event to the div with class myBox, then it finds the link's src attribute inside the div and window.location is used to redirect the page to the src attribute of the link present inside the div. So this basically makes the div clickable.


If you're saying you want the entire div to be clickable for navigation, then you can either wrap it with an anchor () tag, which is not standards compliant, or add a css style to the contained anchor tag, making it the size of the containing div, which is standards compliant. I will use a div that is 250px by 250px in this example:

<div id="container"><a href="" style="display:block;width:250px;height:250px;">Link</a></div>


I ran into this problem last year. I simply added an onclick to the div. Like so: <div id="testimonial" style="cursor:pointer;" onclick="document.location='http://www.mysite.com/testimonials.html'">


In HTML5 it is now valid to have a div or whatever inside an a. That should do the trick. No scripts needed, unless that's what's in your link.


You can use a JavaScript code at to achieve your goal, please take a look at this tutorial.

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

and this is the HTML example :

<div class="myBox">
     blah blah blah.
    <a href="http://google.com">link</a></div>

but there is a tricky way to achieve this using a CSS code you must nest an anchor tag inside your div tag and you must apply this property to it,

display:block;

when you've done that,it will make the whole width area clickable (but within the height of the anchor tag),if you want to cover the whole div area you must set the height of the anchor tag exactly to the height of the div tag,for example:

height:60px;

this is gonna make the whole area clickable,then you can apply text-indent:-9999px to anchor tag to achieve the goal.

this is really tricky and simple and it's just created using CSS code.

here is an example: http://jsfiddle.net/hbirjand/RG8wW/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜