Trying to find an attribute that contains "launch-overlay-", so even there are other classes before and after, the scrip will still work. After finding it, add the "active" class to the match number div. This is what I have so far, but if there other class around the "launch-overlay-", it won't work. >< Help plz.
$('div[class*="overlay-"]').click(function(){
var overlaynum = $(this).attr('class').match(/\d+$/)[0];
$('.overlay-container-'+overlaynum).addClass('-active');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class=“other-class overlay-1”>click me</div>
<div class=“other-class overlay-2”>click me</div>
<div class=“overlay-container-1”></div>
<div class=“overlay-container-2”></div>
You can use a capture group to get the overlay number only when it appears after launch-overlay-
:
var overlaynum = this.className.match(/launch-overlay-(\d+)/)[1];
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^ ^^^−−− capture group 1
Note that I get the number via [1]
instead of [0]
since it's the first capture group (we don't want the full match that's in [0]
).
Live Example (I've had to fix a couple of things in there, but they don't seem related to the question):
$('div[class*="launch-overlay-"]').click(function(){
// Get the number from the relevant class
var overlaynum = this.className.match(/launch-overlay-(\d+)/)[1];
$('.overlay-container-'+overlaynum).addClass('-active');
});
.-active {
color: blue;
font-weight: bold;
}
<div class="other-class launch-overlay-1 other">click me - I have another class</div>
<div class="other-class launch-overlay-2">click me</div>
<div class="overlay-container-1">overlay container 1</div>
<div class="overlay-container-2">overlay container 2</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>