Question

I'm making a DIV clickable like so:

jQuery(".post").click(function(){
    window.location=jQuery(this).find(".post-title a").attr("href");
    return false;
});

but I also want to add rel attribute to it so the link can open in a lightbox. I tried adding .attr("rel=prettyphoto") but it doesn't seem to work.

Was it helpful?

Solution

You should add the rel attribute on page load, not on click, and make sure you do that before you init the lightbox script. There is not point in setting the attribute on click, as the page reload would take place anyway, and the attribute would be gone.

So:

// Inside this block we're sure the DOM is loaded,
// so we can init our stuff
$(document).ready(function() {

    // Add rel to post title links
    $('.post .post-title a').attr('rel', 'lightbox');

    // Now init your lightbox script
    // (your init code here)

    // Now set the click handler (does not have to be last)
    $(".post").click(function(){
        window.location=$(this).find(".post-title a").attr("href");
        return false;
    });

});

OTHER TIPS

It should be:

$("whatever").attr("rel", "prettyphoto");

As the docs note:

attr( name ) is the getter
attr( name, value ) is the setter

if I were you, i'd break it out into steps, you'd actually answer your own question in the process.

jQuery(".post").click(function(){

    // store the link in var
    var link = jQuery(this).find(".post-title a");

    // set the rel
    link.attr('rel','prettyphoto');

    // get the href
    var location = link.attr("href");

    window.location=location;
    return false;
});

Also, do remember that the .attr( attrName [, attrVal] ) method has two arguments: if you write the second argument in your function, it will set a value.

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