Home > Mobile >  jQuery - how to create variable and click event with same class name but different number
jQuery - how to create variable and click event with same class name but different number

Time:05-25

Is there a way to group several variables and click events into one function?

I'd like to only have one function that would call all the classes with the same name but different numbers (from 1 to 3 in this case) so I don't have to make multiple functions like this:

function step1() {
  $("#step-1").fadeIn();
}

function step2() {
  $("#step-2").fadeIn();
}

function step3() {
  $("#step-3").fadeIn();
}

And

$("#step-1-btn").click(function(){
  step1();
});

$("#step-2-btn").click(function(){
  step2();
});

$("#step-3-btn").click(function(){
  step3();
});

I'm sure there is an answer to this question already, but I can't phrase it good enough to find it...

CodePudding user response:

It's not 100% clear to me what you want to achieve, but you can try something like this:

$("button[id^=step-]").click(function() {
  var id = $(this).attr("id").split('-')[1]
  step(id);
});

function step(num) {
  console.log("you called step with number:"   num)
}

The click event will work for any button where the id starts with step-. Then it will split the id and take the number from it and pass it to your function.

Demo (With fadein example)

$("button[id^=step-]").click(function() {
  var id = $(this).attr("id").split('-')[1]
  step(id);
});

function step(num) {
  console.log("you called step with number:"   num)
  $('div[id^=step-]').hide();
  $("#step-" num).fadeIn();
}
#step-1,#step-2,#step-3 {
  height:200px;
  width:200px;
  display:none;
  background-color:yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="step-1-btn">step 1</button>

<button id="step-2-btn">step 2</button>

<button id="step-3-btn">step 3</button>


<div id="step-1">1</div>
<div id="step-2">2</div>
<div id="step-3">3</div>

  • Related