0

I have an object:

var obj = { id: $('#f_view') };

I have a function:

function switchFrom(trigger) {
          trigger.id.click(function() {
                 this.id.toggleClass('class');
          });
};

When i run the function:

switchFrom(obj);

I get :

undefined is not a function (evaluating'this.id.toggleClass('class')')

When I refer to the element explicitly, the function works.

$('#f_view').toggleClass('class');

What Am i doing wrong? Thank you for your time.

3
  • 1
    id is a pretty bad variable name in your case. Should be something like $ele Commented Jun 20, 2015 at 19:04
  • 2
    trigger.id.toggleClass('class'); is what you wanted to do. The answer below is probably better though Commented Jun 20, 2015 at 19:05
  • @StephenBugsKamenar , this way works, thank you. I was just wondering whether same thing can be done with this reference. Commented Jun 20, 2015 at 19:15

1 Answer 1

4

You need to convert to a jQuery object by wrapping in $(...) like

function switchFrom(trigger) {
         trigger.id.click(function() {
                 $(this).toggleClass('class');
          });
}

This is because native javascript objects do not have access to jQuery methods

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

3 Comments

when i have the object set up like: var obj = { id: $('#f_view') }; and I do: $(this).toggleClass('class'); I am still getting the same error.
Sorry i forgot to remove .id reference to the object's property. your solution works.
As a side note, if you want this inside function to refers to object, you need to call() method (or using apply()): jsfiddle.net/qz4odfj8/2

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.