Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make DIV clickable on non-clickable areas?

Tags:

html

jquery

css

I have a <div> which contains a few links (<a> tags) and other elements in it. I want to have the <div> behave like a button, which means whenever the user clicks on every part of it, it should navigate to some link. There are a few solutions like this one: Make a div into a link I can make it work with jQuery too, however, the problem is that I want the <a> tags in the <div> to work like before. I couldn't find any solution which makes this possible. How can I do this?

like image 951
Alireza Noori Avatar asked Jan 16 '12 23:01

Alireza Noori


People also ask

How do I make a div element clickable?

If you absolutely need to use JavaScript, one way is to find a link inside the div and go to its href when the div is clicked. This is with jQuery: $(". myBox").

How do I make a div element not clickable?

How do you make a CSS element not clickable? To make a link unclickable using CSS, you can use the pointer-events property. pointer-events: none; on the link that you want to make unclickable and it will not let you click the link.

Can a div be a link?

You can't make the div a link itself, but you can make an <a> tag act as a block , the same behaviour a <div> has. You can then set the width and height on it. However, this doesn't make a 'div' into a link. It makes a link into a block element.


2 Answers

$('#mydiv a').click(function(e) {
  e.stopPropagation();
});

Events bubble up, that's what they do. This is called propagation. Calling stopPropagation on the jQuery event object should prevent that event from bubbling up to your div that contains it.

jQuery Docs here

And since the event handler does not return false, then the browser default click handling for <a> tags will still be fired, which means the href is followed as normal.

Check out a working example here: http://jsfiddle.net/Squeegy/2phtM/

like image 188
Alex Wayne Avatar answered Nov 04 '22 00:11

Alex Wayne


I think you need an event handler which determines which element triggered the click - something like this

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
        <script>
            $(function() {
                $("#links").click(handler);
            })
            function handler(event) {

                var $target = $(event.target);
                if($target.is("#links")) {

                    window.location = "divlocation.htm"
                }
            }
        </script>
    </head>
    <body>
        <div id="links" style="background: yellow">
            <a href="test1.htm">link 1</a><br>
            <a href="test2.htm">link 2</a>
        </div>
    </body>
</html>
like image 39
Michal Avatar answered Nov 04 '22 00:11

Michal