JQuery: Events with Multiple Selectors Using Variables



***Note that this is my first post. I am working on incorporating a syntax previewer to make the code bits more readable.

I was recently confronted with an issue where I was trying to DRY (“Don’t Repeat Yourself”) my code. DRYing your code is a difficult thing to do when you are a struggling, novice programmer. We have deadlines to meet and things work…why not just leave it and move on? I could, but then I have to ask myself, “Am I getting better or just getting by?”

This is the code that I was starting with. I knew it could be DRYed up because it was clearly repetitive.

$('#ToList').on('click', function() {

$('#ToGrid').on('click', function() {
    $('#Grid').mixitup('toGrid'); //

As you can see, the example I’ve provided works, but it’s very repetitive and not very scalable (what if I need to add more buttons?)

I know it’s possible to cache DOM elements with jQuery, so I started by caching the #Grid, and the two buttons, #listButton and #gridButton.

    var Grid = $('#Grid');
    var $gridButton = $('#ToGrid');
    var $listButton = $('#ToList');

Next, I rewrote my click handler so I could pass in both variables (this doesn’t work…more on that in a moment). This is what I wrote:

    $($gridButton, $listButton).on('click', function() {
        if ($(this).attr('id') === 'ToGrid') {  
        } else if ($(this).attr('id') === 'ToList') {

However, I was surprised to find that this didn’t work either. The click event would fire on the first button, but not the second. Why? I know this works if you add multiple selectors as tags, ids, classes, etc… I tested it.

The solution was to create a single variable that contained all of my grid buttons:

    var $gridButtons = $('#ToGrid, #ToList')

…and to replace the two individual variables associated with the click event with a single variable containing both ids:

    $($gridButtons).on('click', function() {

Presto! It worked. This may not be the best approach, but it is certainly cleaner and DRYer than the initial solution.