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.

3
  • 4
    it should be let a = $(this); Commented Mar 16, 2020 at 4:58
  • 1
    Yha, it works. How? Commented Mar 16, 2020 at 4:59
  • 1
    I suggest you console.log(this) then you will understand how this object works. It points to current execution. It has all the information of that element. Commented Mar 16, 2020 at 5:07

2 Answers 2

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)

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

Comments

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.

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.