FrankDraws
FrankDraws

Reputation: 385

Consolidate Multiple Click Events

Sorry if the title isn't accurate. Not sure how to describe it properly.

I have this and it works great:

$(document).on('click', '.flrapPM01', function(event) { 
    toggleDiv('premiereModal01');
});

$(document).on('click', '.flrapPM02', function(event) { 
    toggleDiv('premiereModal02');
});

$(document).on('click', '.flrapPM03', function(event) { 
    toggleDiv('premiereModal03');
});

But I want to consolidate the above and put it into an external js file.

This is as far as I got:

function fireModal() {
    .on('click', '.flrapPM01', function(event) {toggleDiv('premiereModal01');});
    .on('click', '.flrapPM02', function(event) {toggleDiv('premiereModal02');});
    .on('click', '.flrapPM03', function(event) {toggleDiv('premiereModal03');});
}

And how do I make sure 'click' works when touched on a mobile device?

Thank you in advance!

Upvotes: 0

Views: 53

Answers (1)

Joseph Marikle
Joseph Marikle

Reputation: 78550

There's quite a few different ways you can easily do this. With your current code, You can use a selector such as '.flrapPM01, .flrapPM02, .flrapPM03' or '[class*=flrapPM]' and then you can use a simple regex to extract the number from the class (e.g. /(?!flrapPM)\d+/). Honestly, though, I'd look into using data attributes and passing the ID that way if you have control of the markup. Anyway, here is a quick example:

$(document).on('click', '[class*=flrapPM]', function(event) { 
    var num = this.className.match(/(?!flrapPM)\d+/);
    toggleDiv('premiereModal' + num);
});

function toggleDiv(which) {
    alert(which);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="flrapPM01 btn other class">PM01</button>
<button class="something flrapPM02">PM02</button>
<button class="flrapPM03">PM03</button>

Upvotes: 2

Related Questions