mare
mare

Reputation: 13083

Refactor simple jQuery toggle selector

I am moving my code from document.ready() to self executing anonymous function. I have already done a few bigger code pieces but I'm mostly struggling with the smaller ones. Like this one:

/**
Advanced properties toggle
**/
$('a.toggle-link').click(function (e) {
    $(this).next().slideToggle('slow');
    e.preventDefault();
});

How do I refactor this to be able to introduce variables for the selector a.toggle-link (so anything can be passed into the function), for the .slideToggle (so I can pass in the .slideDown, .slideUp, ...) and for the slow?

Upvotes: 3

Views: 204

Answers (1)

David Thomas
David Thomas

Reputation: 253416

This approach uses jQuery, though I've stuck with native DOM methods for the most part:

function actOnElem(el, method, duration) {
    // if no passed 'el' or 'method' return
    if (!el || !method) {
        return false;
    }
    else {
        // if 'el' is an element-node, use 'el' else assume it's an id
        el = el.nodeType == 1 ? el : document.getElementById(el);
        // duration is used if passed, otherwise 'slow' is used as the default
        duration = duration || 'slow';
        // create a jQuery object from 'el',
        // call the method, if it exists,
        // and use the 'duration'
        $(el)[method](duration);
    }
}

actOnElem(document.getElementById('two'), 'slideDown', 1000);

JS Fiddle demo.

Please note that there are no sanity checks, so if the element is already visible and you call the function with slideDown then nothing will happen. Though while I think this answers your question I'm entirely unsure why you want to take this approach, rather than directly calling upon the jQuery methods.

Slightly-revised function to allow for an (incredibly simple) failure reporting:

function actOnElem(el, method, duration, debug) {
    if (!el || !method) {
        return false;
    }
    else {
        el = el.nodeType == 1 ? el : document.getElementById(el);
        duration = duration || 'slow';
        if ($(el)[method]) {
            $(el)[method](duration);
        }
        else if (debug) {
            console.log('Did you make a typo? There seems to be no "' + method + '" method.');
        }
    }
}

actOnElem(document.getElementById('two'), 'slidedown', 1000, true);
//                                              ^
//                                              +--- typo, should be 'slideDown'

JS Fiddle demo.

Upvotes: 3

Related Questions