Search code examples
javascriptjqueryplugins

Why am I having the jquery error Expected an assignment or function call and instead saw an expression?


I'm having an error - Expected an assignment or function call and instead saw an expression. It is written in a jQuery custom plugin code. Can anybody help ? returnin the funtion body works neither

(function ($) {
  $.fn.moveAnimate = function () {
    $(".move").animate(
      {
        position: "absolute",
        left: "150px"
      },
      1000
    );
  };
});


Solution

  • It's because you're attempting to use jQuery's animate method directly inside the plugin definition. To define a custom jQuery plugin correctly, you should return a function that will be executed when the plugin is invoked. Also, you should be calling the IIFE:

    (function ($) {
     $.fn.moveAnimate = function () {
        return this.each(function () {
          // Inside this function, "this" refers to each element matched by the selector
          var $element = $(this);
    
          $element.animate(
            {
              position: "absolute",
              left: "150px"
            },
            1000
          );
        });
      };
    })(jQuery);
    

    You can then use it on your selection of elements like so:

    $(document).ready(function () {
      $(".move").moveAnimate();
    });