2

I am very new in jQuery. I wrote a code

$(document).ready( function() {
        a= $( '.play' ).click( function() {
                let a = this;
                a.css( 'background-image', 'url(pause.svg)' );
                return a;
        } );
)};

Then when I console a, I get the correct result also a.css is referring to jQuery. but when i clicking on the element a type-error returned.

TypeError: a.css is not a function

Maybe I am not yet properly understand async JavaScript call. My question is, why I am getting this error? How jQuery handle this keyword in to the Array Function?

--- Problem Solved ---

I found this vs $(this) discussion is my answer.

Bapi
  • 309
  • 1
  • 16

2 Answers2

2
let a = this;

needs to be

let a = $(this); // now it will create an object of current click element.

I think below code will work perfectly as well,try it.

$(document).ready( function() {
    $( '.play' ).click( function() {
        $(this).css( 'background-image', 'url(pause.svg)' );
    });
)};

Note: this refer to a javascript object and work in a different manner.For more details read below links(regarding what it is, how it works based on different mode and way of calling)

javascript this

this vs $(this)

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
1

you just need to understand basic.

this -> Html DOM element. //the classic JavaScript API is exposed here
$(this)-> $() + this -> you are passing element in a jQuery Constructor-> JQuery object. // jQuery API is exposed

So when you do that you are enabling jQuery Object so you can play with it.

Negi Rox
  • 3,828
  • 1
  • 11
  • 18