Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use a created function in JQuery

My problem is that I cannot use the function I have created. You can see the codes below. I am getting a "not a function error".

var alteropacity = function () {                 //creating function
    if ($(this).css('opacity') < '0.90') {
        $(this).css('opacity', '1.00');
    }
    else {
        $(this).css('opacity', '0.20');
    }
    return $(this);
};
$("#image").on("click", function () {           //using it
    $(this).alteropacity(); 
});
like image 779
SophisticatedUndoing Avatar asked Sep 27 '26 00:09

SophisticatedUndoing


1 Answers

To make a function available as a jQuery method, you have to add a property to $.fn:

$.fn.alteropacity = alteropacity;

Add that right after the function declaration (outside the event handler).

Now, while your code will work, if you really want to make a jQuery method it should follow convention (if that's meaningful for the function's purpose). In this case, it just means iterating:

var alteropacity = function () {
    return this.each(function() {
      if ($(this).css('opacity') < '0.90') {
        $(this).css('opacity', '1.00');
      }
      else {
        $(this).css('opacity', '0.20');
      }
    });
};

That way the method will work if you were to do something like

$(".common-class").alteropacity();

That is, if you were to use the function to affect many elements. Also note that in a jQuery method this refers to the jQuery object for which the method is being invoked. It doesn't hurt to wrap it again ($(this)) but you don't have to. Inside the .each() iteration, however, you're back in familiar territory so this inside that callback will refer to the elements involved.

like image 89
Pointy Avatar answered Sep 28 '26 16:09

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!