Search code examples
jqueryfunctioneventsstoppropagation

e.stopPropagation works but presents error in console


Here's my code, it works but the console gives me this message:

Uncaught TypeError: Object 2 has no method 'stopPropagation'

This is my code:

$(".addtag").click(function () {
    var current_id = $(this).parent().attr("id");
    $('div .tag').each(function (e) {
        var this_tag_id = $(this).attr("id").replace("tag", "");
        if (this_tag_id == current_id) {
            alert("You can't tag an item twice");
            e.stopPropagation();
        }
    });
$("body").css("color","red"); <--- if (this_tag_id == current_id) I want to prevent this from executing.
}

Any suggestions?


Solution

  • You've declared e as the argument to each, not as the argument to your event handler, and so e is a DOM element, not an event object, and doesn't have stopPropagation. Move the e argument out of the each function and into the function handling the click.

    $(".addtag").click(function(e) {
    // Here --------------------^
    var current_id = $(this).parent().attr("id");
      $('div .tag').each(function(){
    // Not here ------------------^
          var this_tag_id = $(this).attr("id").replace("tag","");
          if (this_tag_id == current_id) {alert("You can't tag an item twice"); e.stopPropagation();}
      });
    }
    

    Re your comment below:

    $(".addtag").click(function (e) {
        var current_id = $(this).parent().attr("id");
        $('div .tag').each(function () {
            var this_tag_id = $(this).attr("id").replace("tag", "");
            if (this_tag_id == current_id) {
                alert("You can't tag an item twice");
                e.stopPropagation();
            }
        });
        $("body").css("color", "red"); // <-- I want to prevent this from executing if this_tag_id == current_id.
    });
    

    Set a flag in your each, and check it after:

    $(".addtag").click(function (e) {
        var current_id = $(this).parent().attr("id");
        var iscurrent = false;       // <=== Flag
        $('div .tag').each(function () {
            var this_tag_id = $(this).attr("id").replace("tag", "");
            if (this_tag_id == current_id) {
                iscurrent = true;    // <=== Set
                e.stopPropagation(); // <=== Put this above alert
                alert("You can't tag an item twice");
            }
        });
        if (!iscurrent) {            // <=== Add check
            $("body").css("color", "red");
        }
    });