Macsupport
Macsupport

Reputation: 5444

Setting a rel attribute dynamically

I am using PrettyPhoto lightbox, and trying to set a rel attribute on a link when another non-jQuery javascript library makes that link active (it sets the links class to active) so the PrettyPhotot lightbox will open. I don't want the link to open unless it is an active link. I am successful in setting the attribute, but every link opens in the lightbox when clicked, not just the active one. No errors in FireBug.

Prettyphoto's code is set as so:

$("a[rel^='prettyPhoto']").prettyPhoto();

The other javascripts code for the active and inactive click:

ContentFlowConf: {
    onclickActiveItem: function (item) {
        $('.active').attr('rel', 'prettyPhoto[gallery]');
    },
    onclickInactiveItem: function (item) {
    $('.active').removeAttr('rel');
        $('.item').click(function(event) {
            event.preventDefault(); 
        });
    }
}

The initial html is:

 <a class="item" title="Image" href="image.jpg"><img class="content" src="thumb.jpg" alt="Image"/></a>

The other javascript sets the html to:

 <a class="item active" title="Image" href="image.jpg"><img class="content" src="thumb.jpg" alt="Image"/></a>

I am of course a novice and not sure what will make it work. I am wondering if the .live function might need to be used?

Upvotes: 0

Views: 5377

Answers (2)

Macsupport
Macsupport

Reputation: 5444

Solved this a follows:

onclickActiveItem : function(){
    initCBox();
},

//lots of code here...

function initCBox(){
    var img1 = $('.item.active').attr('href');
    var label = $('.item.active .content').attr('alt');
    $.prettyPhoto.open(img1, label);
}

Upvotes: 0

casablanca
casablanca

Reputation: 70701

The problem is that once you call

$("a[rel^='prettyPhoto']").prettyPhoto();

those links are registered to open in prettyPhoto. Changing the rel attribute later doesn't affect the event handlers already set up by prettyPhoto.

I looked at the docs for prettyPhoto and it appears there is another way to manually open an image:

$.prettyPhoto.open('image.jpg','Title','Description');

So when the user clicks a link, you could check if it is active and if so, manually open prettyPhoto. Something like this might work: (not tested)

$('a.item').click(function() {
  var link = $(this);
  if (link.hasClass('active'))
    $.prettyPhoto.open(this.href, link.text(), '');
});

Upvotes: 3

Related Questions