Markus Markus - 3 months ago 14
Javascript Question

jquery animate() does not work in prototype

Why does this jquery function not work if I call the prototype?

$("#demo").animate({left: '250px'});


The function before for changing the bg-color works well.

Complete Code:

<body>
<style>
#demo{width: 400px;}
button {padding: 10px; background-color: #3f8aca; color: #fff; border-radius: 3px; margin:100px 0 0 100px; border: none;}
</style>
<div id="demo"></div>
<button onclick="porsche.drive();">My Porsche drives.</button>

<script>
function Car(){}
var porsche = new Car(), lancia = new Car();
Car.fn = Car.prototype;

Car.fn.drive = function drive(){
console.log("Yeahh, I´m driving there!");
document.getElementById("demo").innerHTML = "Yeahh, I´m driving there!";
$("#demo").css("background-color","red");
/* the function below dont works */
$("#demo").animate({left: '250px'});

}
Car.fn.stops = function stops(){
console.log("Oh, I´ve to stop here!");
}
lancia.stops();
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

</body>


Thanks for your advice,
Markus

Answer

You must add position: relative; like this :

#demo {
    width: 400px;
    position: relative;
  }

and add duration option :

$("#demo").animate({left: '250px'},{duration:2000});

Final code :

<body>
  <style>
    #demo{
        width: 400px;
        position: relative;
      }
    button {padding: 10px; background-color: #3f8aca; color: #fff; border-radius: 3px; margin:100px 0 0 100px; border: none;}
  </style>
  <div id="demo"></div>
  <button onclick="porsche.drive();">My Porsche drives.</button>

<script>
  function Car(){}
    var porsche = new Car(), lancia = new Car();
    Car.fn = Car.prototype;

    Car.fn.drive = function drive(){
    console.log("Yeahh, I´m driving there!");
    document.getElementById("demo").innerHTML = "Yeahh, I´m driving there!";
    $("#demo").css("background-color","red");
    /* the function below dont works */
    $("#demo").animate({left: '250px'},{duration:2000});

  }
  Car.fn.stops = function stops(){
    console.log("Oh, I´ve to stop here!");
  }
lancia.stops();
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
    
    </script>
</body>