jquerycallbackfancyboxfancybox-2

Fancybox beforeLoad Callback: Javascript, jQuery and referencing $this?


I'm not sure how to accomplish what I'm looking to do, which, on starting out, seemed simple. I want to add a 'visited' class to a clicked link before calling the linked content into a fancybox iframe.

Fancybox works fine, as long as I leave off the beforeLoad call. When added, the page simply reloads the window, bypassing the Fancybox.

I'm not sure whether my beforeLoad function (here called add_visited) is allowed to use jQuery (as in addClass), or whether I need to stick to straight javaScript functionality (element.setAttribute("className", "visited")). The code pasted here is for jQuery, with a reference to a passed this in theClicked.

So, as you can see, I'm also not sure how to refer to $(this) in the function. Essentially I want to carry over this from the actual $.fancybox() call.

And, for clarity, .clinical_trial_link is a class applied to an anchor. In the actual code it's a.clinical_trial_link.

For further clarity, I've read a few conversations here discussing the relative merits of this method of marking links as visited. I get the downside to simply using a class, but on a site as link heavy as this one, seeing what's been clicked already is imperative.

Finally, the page in question is located here: http://pull4parkinsonsfoundation.org/clinical_trials/

The js, of course, will change from what's pasted here as I continue to thrash around like a mackeral with a keyboard. ;-)

Any help would be appreciated, and thanks in advance for the excellent work you all do on stackoverflow. This is the first time I've actually had to post a question in years!

Here's my code:

function add_visited(theclicked) {
    $(this).addClass('visited');
}

$(document).ready(function() {
    $('.clinical_trial_link').fancybox({
        'beforeLoad': add_visited($this),
        'maxWidth': 1222,
        'maxHeight': 1222,
        'fitToView': true,
        'width': '80%',
        'height': '90%',
        'topRatio': 0.2,
        'autoSize': false,
        'closeClick': false,
        'openEffect': 'elastic',
        'closeEffect': 'elastic'
    });
});

Solution

  • If what you want to do is to add a class to the selector bound to fancybox, refer to that element using $(this.element) within any of the fancybox callbacks like

    $('.clinical_trial_link').fancybox({
      'beforeLoad': function(){
        $(this.element).addClass("visited");
      },
      'maxWidth': 1222,
      // other API options etc
    });