tags:

views:

48

answers:

3

I have added stopPropagation, however, I still get two popups in a row. This is better than before, where there were 20 popups for one element that is clicked....is there a better approach or am I missing something ?

$(top.document).ready(function () {

    $("*").click(processAction);

});

function processAction(e) {
    var clicked = e.target;
    e.stopPropagation();
    alert(clicked.tagName);
    e.stopPropagation();
    switch (clicked) {
    case "A":
        //execute code block 1
        break;
    case "INPUT":
        //execute code block 2
        break;
    default:
        //code to be executed if n is different from case 1 and 2
    }
};
A: 

use

$('*').each(map, function(key, value) { 
   $(this).click(processAction);

});

instead;

lock
jQuery `.each()` only accepts one argument, so what is the `map` argument? If you use `.each()`, you'll have the same result as the code in the question.
patrick dw
Sounds like conflating `$.each()` and `$(...).each()` to me.
Matt Ball
A: 

My little advice: replace * with a or input. Now your code will be more simpler, u could be able remove switch. (I see in switch you inspect what element was clicked).

Rin
+1  A: 

I'd say definitely do not place a click handler on every element. As @Rin stated, you can assign them by tag, or some other selector.

If you really want to process all clicks on the page that way, I'd suggest that you place one handler on the document, and let the click events bubble up to that.

This is much more efficient and there's no need to do e.stopPropagation().

Example: http://jsfiddle.net/y6hry/

$(top.document).ready(function () {
       // All clicks on the page will bubble up to the document
       //   and fire the handler.
    $(document).click(processAction);
});

function processAction(e) {
    var clicked = e.target;
    alert(clicked.tagName);
    switch (clicked.tagName) {
    case "A":
        //execute code block 1
        break;
    case "INPUT":
        //execute code block 2
        break;
    default:
        //code to be executed if n is different from case 1 and 2
    }
};
patrick dw