willbeing
willbeing

Reputation: 425

jQuery add function parameter or variable into id selector

Say you have 10-15 fixed divs that you'd like to animate() with different parameters. Using jQuery, what's the best method to pass different parameters for each div? My current method, below, attempts to pass the id text in the function. This is the first step, and eventually I imagine I'd pass the animation() duration and rotation in as function parameters (e.g. float(ID, duration, rotation)It now returns the following: Error: Syntax error, unrecognized expression: "#candy"

$(document).ready(function () {
    float("candy");
    float("candy2");
    //etc
});

function float(ID) {
    let id = "#" + ID;
    $('"' + id + '"').animate({
        top: 100,
      }, 5000 );
};

Upvotes: 0

Views: 400

Answers (2)

Sami
Sami

Reputation: 2110

You don't need to declare the scoped variable at all. Just pass the parameters from the function call to the method.

$(document).ready(function () {
    float("candy", 5000);
    float("candy2", 2000);

});

function float(ID, duration) {
    $('#' + ID).animate({
    top: 100,
  }, duration );
};
#candy {
  background-color: red;
  width: 200px;
  height: 200px;
  position: relative;
  }
 #candy2 {
  background-color: yellow;
  width: 200px;
  height: 200px;
  position: relative;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div id="candy"></div>
<div id="candy2"></div>
</div>

Upvotes: 1

Vishnu
Vishnu

Reputation: 897

I think you need the function like:

function float(ID) {
 let id = "#" + ID;
 $(id).animate({
    top: 100,
  }, 5000 );
}

Upvotes: 0

Related Questions