views:

21

answers:

1

What is the best way to write this function ontop of jQuery.

Background: I'm working on a legacy web app that has lots of issues. It requires us to insert a IFrame to take care of a few "screens". Later this code will be refactored out but for now we need this.

function openIframePage(selectorPath, url) {
    if ($(selectorPath).length > 0) {
      $('#ifrPage').attr('src', url);
    } else {
      $(selectorPath).append('<iframe id="ifrPage" src="' + url + '" />');
    }
}
function closeIframePage() {
     $('#ifrPage').remove();
}

Is there a better way to write this? How do most people pass around selectors? or do they pass around the jQuery object itself? Not looking for a plug-in. Thanks.

+3  A: 

I would make the function take an actual jQuery object as a parameter, and call $ when passing the parameter.
This means that the selector will only be evaluated once.

For example:

function openIframePage(elem, url) {
    if (elem.length > 0) {
      $('#ifrPage').attr('src', url);
    } else {
      elem.append('<iframe id="ifrPage" src="' + url + '" />');
    }
}

For maximum flexibility, you can write elem = $(elem), then pass almost anything.

SLaks
Is it normal to call it elem? I mean I know you can. But I thinking from a style perspective since its really the jQuery object.
tyndall
I'm not sure. You might call it `obj` or `target`, or perhaps `iframe`.
SLaks
never tried this before but $($("#myDiv")) == $("#myDiv") ?
tyndall
It will return a separate jQuery object with the same contents.
SLaks