0

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 );
};
1
  • You are double passing quotes, causing it to respond as if you have something similar to this: ""#candy"" instead of "#candy", there is no need to do: '"' + id + '"' Do only $(id) and you should be fine on the error, side. Commented Jan 27, 2020 at 20:10

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Sami. I initially did this but ran into the following error: TypeError: $('#' + ID).animate is not a function. (In '$('#' + ID).animate({ top: 100, }, duration )', '$('#' + ID).animate' is undefined)
Are you using slim build of jQuery or the full version? The slim one doesn't include some of the functions, .animate being one of them.
0

I think you need the function like:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.