How do I create a click event handler inside a mouseover event handler?

I'm trying to create some sort of item inspector (in Chrome / FF for example).

The stream looks like this:

  • Click the "Start Checkout" button.
  • Move the cursor over the required item.
  • You click on this item.
  • You should see this item in the console.

JSFiddle example

Here is the code:

startInspecting = function(){
    $('section *').on('mouseover.INSPECTOR', function(e){
        $('.hovered-element').removeClass('hovered-element');
        $(e.target).addClass('hovered-element');
        $(this).on('click.INSPECTOR', function(e){
            $('section *').off('mouseover.INSPECTOR');
            $('section *').off('click.INSPECTOR');
            $('.hovered-element').removeClass("hovered-element");
            console.log(e.target);
        });
    });
};

      

Problem : Every time I hover over any event handler element, it attaches to it. So, if I visit an item p

5 times and then click on it - I see 5 console.log

instead of 1
.

I tried to implement it using mouseenter/mouseleave

, but ran into the problem that each element can be hovered only once - another example JSFiddle

So how can I improve my code, no matter how many times I overlay an element on it, it will only have one click handler?

Thanks in advance, any help would be appreciated!

+3


source to share


2 answers


Have you tried moving the handler onclick

out mouseover

?

startInspecting = function(){
    $('section *').on('mouseover.INSPECTOR', function(e){
        $('.hovered-element').removeClass('hovered-element');
        $(e.target).addClass('hovered-element');        
    }).on('click.INSPECTOR', function (e) {
        $('section *').off('mouseover.INSPECTOR click.INSPECTOR');
        console.log(e.target);
    });
};

      



DEMO

+3


source


I suggest breaking it down into parts. The user clicks the Start Checkout button and your page goes into checkout mode where it dynamically adds css to each element that hovers, so it looks like Chrome. When you click on an element in checkout mode, you can treat it however you want. This way you only need to add one pointer control and one click for each item, thus only firing the event once.



0


source







All Articles