Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Click on *only* this element

Super-technical drawing

In the highly-artistic drawing above, the green square is a child of the pink one. The pink one is wrapped around the green one by my function, so the green square could be anything - a hyperlink, an image, button, etc.

I want to capture a click on the pink div ONLY if it isn't a click on the green element too.

This could be done by flipping a Boolean using mouseenter on the green square, but that seems a messy way to do it to me.

Any clues?

IMPORTANT EDIT: I can't mess with the green square at all, so no adding anything to the click event.

like image 666
Grim... Avatar asked Sep 14 '11 14:09

Grim...


People also ask

How do you make a button click only once in jQuery?

You can use jquery . one() This will ensure that the click event happens only once.

How call jQuery function only once?

jQuery one() Method The one() method attaches one or more event handlers for the selected elements, and specifies a function to run when the event occurs. When using the one() method, the event handler function is only run ONCE for each element.

How do you attach a event to element which should be executed only once?

Approach 1: In this approach, we will be using the jQuery one() method. This method attaches an event to the element with the specified selector. It is named one because the event handler corresponding to the event is only executed once.

How do I trigger a click event without clicking?

If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.


1 Answers

You can do this:

$('.pink-box-selector').click(function(e) {
    if ($(e.target).is('.pink-box-selector')) {
        // do stuff here
    }
});
like image 132
jmar777 Avatar answered Nov 06 '22 12:11

jmar777