3

I have two images stacked one above the other. img_top has 'pointer-events: none' set, so clicking on it will pass the click to img_bottom. However if I invoke jQuery's trigger('click') on img_top, the click will not pass on to img_bottom.

Can anybody explain why and find a way of passing the click to the bottom image using jQuery's trigger('click') AND CSS's pointer-events?

Here is the code I am using:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<style type="text/css">
    #img_holder {
        position: relative;
        width: 20px;
        height: 20px;
    }

    #img_bottom {
        position: absolute;
        background: url('/images/cross.png');
        width: 16px;
        height: 16px;
        z-index: 1;
    }

    #img_top {
        pointer-events: none;
        position: absolute;
        background: url('/images/tick.png');
        width: 16px;
        height: 16px;
        z-index: 2;
    }
</style>

<script type="text/javascript">
    $(document).ready(function() {
        $(document).click(function() {
            alert('clicked');
            $("img_top").trigger('click');
        });

        $("#img_bottom").click(function() {
            alert('success');
        });
    });
</script>

<div id="img_holder">
    <div id="img_top"></div>
    <div id="img_bottom"></div>
</div>

1 Answer 1

4

This is because in javascript events bubble up the DOM. img_bttom is a sibling of img_top, so the event would never bubble to it.

You can force it manually though:

$("#img_top").click(function(event) {
    $("#img_botton").trigger(event);
})
Sign up to request clarification or add additional context in comments.

6 Comments

This works correctly, but why doea a "real" click then pass through? And how to emulate it?
@AdrienHingert a real click passes through because it is handled by the browser's UI, which looks at mouse position and determines the correct element to raise the event on.
Is there any way that this can be "faked" via JS in such a way that it would pass through as per my example above?
I would need it to go through one image with the pointer-events set to none. Your example skips this.
You say in the OP img_top has 'pointer-events' set to none, so clicking on it will pass the click to img_bottom. However if I invoke jQuery's trigger('click') on img_top, the click will not pass on to img_bottom. This code fixes that problem.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.