Alireza Noori
Alireza Noori

Reputation: 15253

How to make DIV clickable on non-clickable areas?

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?

Upvotes: 5

Views: 1156

Answers (2)

Michal
Michal

Reputation: 13639

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>

Upvotes: 1

Alex Wayne
Alex Wayne

Reputation: 187034

$('#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/

Upvotes: 4

Related Questions