简体   繁体   中英

How to make onClick event fire for child image element inside div

I have a td with a div with a child image inside. The CSS targets this div, and the onclick event is on the div that fires off some jquery to create a pop-up with an overlay div behind it.

Problem: I can click on any area in the div and the onClick event is triggered EXCEPT for when I click on the image inside the div.

Here is the code:

<td>
<div id="send_a_message_tile_div" onclick="fadeToggle()">
<img src="dr-icon-white.png" alt="Send A Message" title="Send A Message" 
width="120" height="120">
<span>Send A Message</span>
</div>
</td>

Here is the jQuery:

var fadeToggle = (function() {
$(document).on("click",function (e) {
switch(e.target.id) {
    case 'send_a_message_tile_div':   $('#send_a_message_div').addClass('popup_menu').removeClass('make_invisible');
            $("#overlay_background").fadeIn(300);
            $("#send_a_message_div").fadeIn(500);
            //e.stopPropagation(); 
            return false;
    break;

Do I need to add something like e.ContineuePropagation()? lol

Here is the CSS:

#img_icons_table td div{
    font-family: 'Ubuntu', sans-serif;
    text-align:center;
    position: relative;
    width:170px;
    height:155px;
    margin:5px 5px 30px 5px;
    border-radius: 5px;
    padding:5px;
    padding-top: 15px;
    box-shadow: 1px 1px 8px gray;
    background: #31b44b;
    transition: 0.1s all ease;
    cursor:pointer;
}
#img_icons_table td div:hover{
    font-family: 'Ubuntu', sans-serif;
    background:#448e40;
    box-shadow: 5px 10px 10px #aaaaaa;
}  
#img_icons_table td div img{
    font-family: 'Ubuntu', sans-serif;
    position: relative; 
    border-radius: 6px;
     opacity: 0.85; 
    filter: alpha(opacity=85); /* For IE8 and earlier */
} 

I have even tried attaching the onClick event on just the image, but it still only fires when clicking outside the image, but inside the div...??

See images, below:

Before onclick event

After onClick event is fired

How can I make the image inside the div with the onClick even also fire the onClick event when the image is clicked?

Any help is greatly appreciated!

The problem is that e.target will always be the thing that was clicked on, so even if the event bubbles up after clicking on an image, e.target will remain a reference to the image for every handler that is called, not the current item. Also, propagation and bubbling only concern other event handlers on the element your event is attached to, or its ancestors. The event does not fire for each item between the element that has the event and the descendant that was clicked. The event will only fire once per click.

You appear to be trying to use event delegation . You could use .closest() to find the element that you are looking for, but luckily jQuery provides an easier way to do it. The best way to do event delegation with jQuery is by passing a selector string to .on as the second parameter after the event type. When you do this, the first ancestor of the thing that was clicked that matches the selector will fire the event handler and be assigned to this . You can then test this.id instead of e.target.id .

Also, instead of attaching the event handler to the document , it would be better to attach it to the closest common ancestor of all the elements you are targeting, in this case it is probably the table they are all contained in. Likewise, instead of inlining a click handler that then attaches a handler, just attach the handler to begin with.

 // Attach to the #actions table // targeting the divs $('#actions').on('click', 'div', function(e) { // since we passed a 'div' selector to .on, // this will be an element that matches that selector switch (this.id) { case 'inbox_div': alert('Inbox clicked'); e.stopPropagation(); break; case 'send_a_message_tile_div': alert('Send A Message clicked'); e.stopPropagation(); break; } }); 
 #actions div { border: 1px solid #090; background: #090; border-radius: 7px; padding: 1em; margin: 1em; } #actions span { display: block; text-align: center; color: #fff; font-family: sans-serif; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="actions"> <tr> <td> <div id="inbox_div"> <img src="http://via.placeholder.com/150x150" alt="Send A Message" title="Send A Message" width="120" height="120"> <span>Inbox</span> </div> </td> <td> <div id="send_a_message_tile_div"> <img src="http://via.placeholder.com/150x150" alt="Send A Message" title="Send A Message" width="120" height="120"> <span>Send A Message</span> </div> </td> </tr> </table> 

Here I'm using 'div' as the selector to filter out the elements we want to target this event to. If you can't use 'div' , for instance if it is possible the <div> s could themselves contains <div> s, you could instead add a class to the elements you want to target and then use that class as the selector:

 $('#actions').on('click', '.event-target', function(e) { switch (this.id) { case 'inbox_div': alert('Inbox clicked'); e.stopPropagation(); break; case 'send_a_message_tile_div': alert('Send A Message clicked'); e.stopPropagation(); break; } }); 
 #actions div { border: 1px solid #090; background: #090; border-radius: 7px; padding: 1em; margin: 1em; } #actions span { display: block; text-align: center; color: #fff; font-family: sans-serif; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="actions"> <tr> <td> <div id="inbox_div" class="event-target"> <img src="http://via.placeholder.com/150x150" alt="Send A Message" title="Send A Message" width="120" height="120"> <span>Inbox</span> </div> </td> <td> <div id="send_a_message_tile_div" class="event-target"> <img src="http://via.placeholder.com/150x150" alt="Send A Message" title="Send A Message" width="120" height="120"> <span>Send A Message</span> </div> </td> </tr> </table> 

Fixed!

Since I forgot to mention, after the 'pop-up' divs open up, they also need the ability to be clicked on to 'close' or set back to invisible.

I removed the onclick="fadeToggle()" from the HMTL and just fixed the Javascript thanks to @uselesscode. These are all DIV's I need to interact with, and since these DIVS are outside the table, using the table ID did not work. This did:

$(document).on('click', 'div', function(e) {

Final code:

$(document).on('click', 'div', function(e) {
// since we passed a 'div' selector to .on,
// this will be an element that matches that selector
switch (this.id) {
    case 'send_a_message_tile_div':
            $('#send_a_message_div').addClass('popup_menu').removeClass('make_invisible');
            $("#overlay_background").fadeIn(300);
            $("#send_a_message_div").fadeIn(500);
            e.stopPropagation();
            return false;           
    break;
    case 'send_a_message_div':
            $("#send_a_message_div").fadeOut(300);
            $("#overlay_background").fadeOut(500);
            console.log('at the end of send_a_message_div statement, case 2');
    break;
    case 'appointments_tile_div':
            //console.log('in if step, case 2');
            $('#appointments_div').addClass('popup_menu').removeClass('make_invisible');
            $("#overlay_background").fadeIn(300);
            $("#appointments_div").fadeIn(500);
            e.stopPropagation(); 
            return false;
    break;  
    case 'appointments_div':
            $("#appointments_div").fadeOut(300);
            $("#overlay_background").fadeOut(500);
    break;
    default: 
        //console.log('in the default code and target is ' + e.target.id);
        $('#send_a_message_div').css({ display: "none" });
        $('#appointments_div').css({ display: "none" });
        $('#send_a_request_div').css({ display: "none" });
        $('#overlay_background').css({ display: "none" });
}
});

Here is the HMTL:

<div class="Div_icons" align="center">
    <div id="overlay_background"></div>
        <div id="appointments_div" class="make_invisible">

        <span style="text-align:center"><b><h1>Appointments</h1></b>
            <span></span>

            <br>
            <ul class="popup_menu_ul">

                <li>
                    <a href="https://website.com/schedule-an-appointment/default.aspx">Schedule Appointment</a>
                    <a></a>
                </li>

                <li>
                    <a href="https://website.com/cancel-an-appointment/default.aspx">Reschedule Appointment</a>Cancel Appointment</a>
                    <a></a>
                </li>

                <li>
                    <a href="https://website.com/request-an-appointment/default.aspx">Reschedule Appointment</a>
                    <a></a>
                </li>
            </ul>
        </span>
    </div>
        <div>
        <table id="img_icons_table" class="">
            <tbody>
                <tr>
                    <td>
                        <div id="send_a_message_tile_div">
                            <img src="dr-icon-white.png" alt="Send A Message" title="Send A Message" width="120" height="120">
                            <span>Send A Message</span>
                        </div>
                    </td>
                    <td>
                        <div id="appointments_tile_div">
                            <img src="calendar-icon-white.png" alt="Appointments" title="Appointments" width="120" height="120">
                            <span>Appointments</span>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

Yes I realize this is clunky and not optimal, unfortunately I'm working inside the source page of a WYSIWYG html editor.

关于点击事件也会与图像发生什么关系?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM