dneez
dneez

Reputation: 41

Remove images from Colorbox dynamically, while Colorbox is open

I have appended buttons to colorbox and bound click events to them, this part is working. One of the buttons should remove currently displayed image from Colorbox array and advance to next if there is any.

What i've tried so far:

1)

$(document).ready( function(){
cboxLinks = $('a.colorbox').colorbox(cboxOpts);

$('body').on('click', 'a.remove-from-favorites', function(){
    // 'a.remove-from-favorites' is appended to colorbox div.
    cboxLinks.splice(0,1); // remove first element from cboxLinks collection.
    $.colorbox.next(); // fails
})
}

2)

$(document).ready( function(){
cboxLinks = $('a.colorbox').colorbox(cboxOpts);

$('body').on('click', 'a.remove-from-favorites', function(){
    // 'a.remove-from-favorites' is appended to colorbox div.
    $('a.colorbox#id').remove(); // remove element from DOM.
    $.colorbox.next(); // fails
})
}

When I call $.colorbox.next() current picture disappears, only overlay is displayed and I can't do anything apart from refreshing the page.

How can I achieve this?

Upvotes: 1

Views: 908

Answers (2)

dneez
dneez

Reputation: 41

My solution. Not the most elegant way, but it works for me.

$('body').on('click', 'a.remove-from-favorites', function(){
    // 'a.remove-from-favorites' is appended to colorbox div.
    toremove = $('a.colorbox#id');
    target = ( toremove.next().length ) ? toremove.next() : ( toremove.prev().length )? toremove.prev() : false;
    toremove.remove();

    if (target) {
        target.find('a.ims-colorbox').trigger('click');
    } else {
        $.colorbox.close();
    }
});

In couple of words:

  • Determine picture to be displayed next is any left.
  • Remove link to current picture from DOM.
  • Trigger 'click' event on next picture's link or close colorbox if there are no pictures left.

Let me know if you find a better solution.

Upvotes: 1

elclanrs
elclanrs

Reputation: 94121

If cboxLinks is a collection of jQuery objects try using slice() instead of splice():

cboxLinks.slice(0,1);

Upvotes: 0

Related Questions