jquery if click is on element, do this, else do that

17,277

Solution 1

Edit: Since writing the answer below, delegate has been superseded by on, which should be used instead.


You can (ab)use the event bubbling that occurs. You attach the click listener to every div with a class circle that will ever be made (that can using jQuery's delegate method), and once you're done dealing with that event, cancel the bubbling, so it won't reach the body click listener.

And, on the body listener, just append the circle.

Something like this:

var circle = $("<div>").addClass("circle").text("Circle!");

$("body").click(function() {
    $(this).append(circle);
});

$("body").delegate(".circle", "click", function(e) {
    $(this).remove();

    //To stop the bubbling up
    e.stopPropagation();
    return false;
});

Or, a simpler approach, simply check the target of the click event using event.target:

var circle = $("<div>").addClass("circle").text("Circle!");

$("body").click(function(e) {
    var target = $(e.target);

    if (target.hasClass("circle")) {
        target.remove();
    }
    else {
        $(this).append(circle);
    }
});

Note: Because I created the circle div as a variable, there could only be one. If you don't want that, you can use jQuery.fn.clone, or just make what you need on the spot.

Solution 2

try:

    $(document).ready(function () {
        $(this).click(function (e) {
            var element = $(e.target);
            // do your job with element, for example you can retrieve its "id"
            alert(element.attr("id"));
        });
    });

Solution 3

You'll want to use the target property of the event.

$('body').click(function (e) {
    if(e.target.hasClass("circle")) {
        $(e.target).remove();
    } else {
        // Create circle
    }
});
Share:
17,277

Related videos on Youtube

owenmelbz
Author by

owenmelbz

Updated on June 04, 2022

Comments

  • owenmelbz
    owenmelbz almost 2 years

    This is confusing me now. Here is the pseudo code for what im trying to acheive, i need to use click as that hooks with the touch gestures im building with.

    if body is clicked {
        if click has touched .circle {
            remove circle;
        }
        else {
            create circle;
        }
    }
    
  • owenmelbz
    owenmelbz over 12 years
    Thanks for this, i forgot to mention i already had the create and remove function built, i just couldnt get the e.target to work, as i havent heard of it until now, so thanks the e.target is what ive been looking for to use!!
  • owenmelbz
    owenmelbz over 12 years
    ooh thats v nice thanks, but the idea is it needs to be anywhere on the page which is why ive used html as the selector now as its for a touch surface using absolute positioning.
  • GG.
    GG. over 12 years
    Glad others have been able help you. :)