1

i have a normal function which works and when i console log this it returns jQuery.fn.init [small.expand, context: small.expand

My function below:

jQuery(document).on('click', 'h3.shipping-name small.expand', function (e) {
    var me = jQuery(this);
    console.log(me);
    var next = me.parent().next().next();
    if (next.is(":hidden")) {
        me.find('i').removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
    } else {
        me.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
    }
    next.slideToggle();
});

But if i want to get it from another function like this:

var smallExpand = jQuery('h3.shipping-name small.expand');

smallExpand.on("click", function () {
    expandDetails();
});

function expandDetails(e) {

    alert("oki2");
    var me = jQuery(this);
    console.log(me);
    var next = me.parent().next().next();
    console.log(next)
    if (next.is(":hidden")) {
        me.find('i').removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
    } else {
        me.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
    }
    next.slideToggle();
}

But it returns only empy object like this: jQuery.fn.init {} What am i doing wrong?

3
  • 1
    Problem with your implementation is that this doesn't refers to current element it refers to window. You could do smallExpand.on("click", expandDetails); or expandDetails.call(this); Commented Jan 19, 2018 at 8:07
  • instead of this use e to get the element clicked Commented Jan 19, 2018 at 8:09
  • try using call expandDetails.call(this) Commented Jan 19, 2018 at 8:11

3 Answers 3

1

Problem with your implementation is that this doesn't refers to current element it refers to window object thus the code doesn't work

You can use call() to set the this value

smallExpand.on("click", function (event) {
    expandDetails.call(this, event);
});

Or, You could just pass the function reference to attach event handler

smallExpand.on("click", expandDetails);
Sign up to request clarification or add additional context in comments.

Comments

0

Set the variable first out side your functions, then you can retrieve it for later.

var me;

Then

function first() {
    me = $(this);
}

Now you can use the variable in another function

function thisorthat() {
    $(‘.class’).val(me);
}

Comments

0

You are calling expandDetails as a static method.

as mentioned by @Satpal, you should just do smallExpand.on("click", expandDetails);.

this exists in the smallExpand.on("click", function() {}); scope, but once you call expandDetails(); it gets lost.

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.