James Morrison
James Morrison

Reputation: 19

Simplify repeating jQuery code

I've set up a modal overlay and have this code which could be simplified, I just don't know how to do it.

In theory there will be more than 6 code blocks, so ideally this should cope with as many as possible. The ID's (1 to 6) are generated dynamically using PHP.

jQuery(function ($) {
// Load dialog on click
$('.open-modal-overlay-1').click(function (e) {
    $('#modal-overlay-1').modal();

    return false;
});

$('.open-modal-overlay-2').click(function (e) {
    $('#modal-overlay-2').modal();

    return false;
});

$('.open-modal-overlay-3').click(function (e) {
    $('#modal-overlay-3').modal();

    return false;
});

$('.open-modal-overlay-4').click(function (e) {
    $('#modal-overlay-4').modal();

    return false;
});

$('.open-modal-overlay-5').click(function (e) {
    $('#modal-overlay-5').modal();

    return false;
});

$('.open-modal-overlay-6').click(function (e) {
    $('#modal-overlay-6').modal();

    return false;
});

});

Can anyone help?

Upvotes: 1

Views: 170

Answers (2)

David Hedlund
David Hedlund

Reputation: 129792

The best implementation depends on what factors we can assume about the rest of your markup.

Can we assume that all open-modal-overlay-* should have this click listener? Can we assume that this is the only class they have? In that case, we could do something like:

$('*[class^=open-modal-overlay-]').click(function() {
    var id = $(this).attr('class').slice(-1); // last char of "class" attribute
    $('#modal-overlay-'+id).modal();
});

If we can't assume that this is their only class, then we can't use .attr('class') like that, nor can we use the "class attribute starts with" selector class^=. If they all have another common class, that is unique to them, we could perhaps better access them by $('.open-modal-overlay') (if, say, their class attributes are class="open-modal-overlay open-modal-overlay-2" etc).

If not, we'd have to use the "class attribute contains" selector, class*=, or simply specify the selectors:

$('.open-modal-overlay-1, .open-modal-overlay-2, .open-modal-overlay-3, .open-modal-overlay-4, .open-modal-overlay-5, .open-modal-overlay-6').click(function() {
   ...
});

And we couldn't derive the id variable like that, so we'd have to do something like:

var id = $(this).attr('class').replace(/^.*open-modal-overlay-(\d+).*$/, '$1');

Upvotes: 3

Steve Wilkes
Steve Wilkes

Reputation: 7135

How about:

$([1, 2, 3, 4, 5, 6]).each(function (i, e) {
    $('.open-modal-overlay-' + e).click(function () {
        $('#modal-overlay-' + e).modal();
        return false;
    })
});

Upvotes: 0

Related Questions