Search code examples
jqueryimagejquery-pluginstimercolorbox

Remove colorbox (jQuery plugin) functionality only from one link, and then reapply it


I have two images, each of them wrapped in a link. I want to prevent colorbox from firing if I have been mousedown for more than a certain time. I noticed colorbox fires only on mouseup.

What I have been trying is to use a setTimeout function with a timer, then remove colorbox from that image and on mouseup "reattach" colorbox to that image so it can be fired again if the setTimeout doesn't occur.

HTML:

<a class="colorbox" href="..."><img src="..." /></a>

<a class="colorbox" href="..."><img src="..." /></a>

JS:

$('a.colorbox').colorbox();

var timer;

$('a.colorbox').on('mousedown', function(e) {

    var this_colorbox = $(this);

    timer = setTimeout(function() {
        this_colorbox.colorbox.remove();//this doesn't work
    }, 1500);

}).on('mouseup', function(e) {

    clearTimeout(timer);

});​

//"Reattach colorbox"??

Here is a fiddle: http://jsfiddle.net/mydCn/

The problem I have is $.colorbox.remove(); (or my attempt this_colorbox.colorbox.remove();) removes colorbox from all the elements. How could I "Reattach colorbox" to that image instead of calling the function to every element again (doing so when there are lot of images would affect performance, no?)?


Solution

  • I got it! I could do it just adding and removing classes. I'll publish the answer so it might be helpful to someone.

    http://jsfiddle.net/mydCn/1/

    $('a.colorbox').colorbox();
    
    var timer;
    var time_completed = 0;
    
    $('a.colorbox').each(function() {
        $(this).on('click', function(e) {
            if (time_completed === 0) {
                e.preventDefault();
                $(this).removeClass('colorbox cboxElement');
            } else if (time_completed == 1) {
                $(this).addClass('colorbox cboxElement');
                time_completed = 0;
            }
        });
    
        $(this).on('mousedown', function(e) {
            timer = setTimeout(function() {
                time_completed = 1;
            }, 500);
        }).on('mouseup', function(e) {
            clearTimeout(timer);
            if (time_completed == 1) {
                $(this).click();
            }
        });
    });​