Question

I am making a slider and I detect the position of the mouse to define click event. I create a $(document).on('mousemove') event and when I am on the position I want a click, I add a on('click') event, but in this case, the event it's called so many time, and not just one time.

Let's see this code. Here is a quick example : jsFiddle

var widthScreen = $(window).width();

$(document).on('mousemove', function(e) {
    console.log(e.pageX);

    if (e.pageX > (widthScreen - 120) && e.pageX < widthScreen) {
        $('ul').addClass('right-show');

        $('li').eq(2).on('click', function() {
            console.log('too much click');
        });
    } else {
        $('ul').removeClass('right-show');
    }
});

How can I solve this issue ?

Was it helpful?

Solution

When ever you do the mousemove, it is checking the condition and attaching the click event. So the click event is attached many times. To avoid this, first remove the click event using off('click') and attach it. Here is the updated fiddle.

var widthScreen = $(window).width();

$(document).on('mousemove', function(e) {
    console.log(e.pageX);

    if (e.pageX > (widthScreen - 120) && e.pageX < widthScreen) {
        $('ul').addClass('right-show');

        $('li').eq(2).off('click').on('click', function() {
            console.log('too much click');
        });
    } else {
        $('ul').removeClass('right-show');
    }
});

OTHER TIPS

Remove the event attachment from mousemove handler, and create a flag to check, if the cursor is on correct position:

var widthScreen = $(window).width(),
    onArea = false;

$(document).on('mousemove', function(e) {
    if (e.pageX > (widthScreen - 120) && e.pageX < widthScreen) {
        $('ul').addClass('right-show');
        onArea = true;
    } else {
        $('ul').removeClass('right-show');
        onArea = false;
    }
});

$('li').eq(2).on('click', function(e) {
    if (onArea) {
        console.log('Not too much clicks.');
    }
});

A live demo at jsFiddle.

Have a look at underscore.js throttle function:

_.throttle(function, wait, [options]) 

Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with

Use .one() instead of .on() Here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top