1

This is original function:

$(document).on('click', '.itemove', function() {
    $('.itemoveact').removeClass('itemoveact');
    $(this).addClass('itemoveact');
});

Now I want to do the same by calling another function:

$(document).on('click', '.itemove', function() {
    swclass('itemoveact');
});

function swclass(c){
    $('.' + c).removeClass(c);
    $(this).addClass(c);
}

Nothing happens. There is a problem with passing this context.

Any help?

Michael Hutter
  • 1,064
  • 13
  • 33

4 Answers4

0

You can use Function.prototype.apply()

$(document).on('click', '.itemove', function() {
   swclass.apply(this, ['itemoveact']);
});
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
0

In the swclass function

function swclass(c){
   $('.' + c).removeClass(c);
   $(this).addClass(c);
}

this is just a reference which points to window object.

One solution is to use bind method.

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

$(document).on('click', '.itemove', function() {
    swclass.bind(this)('itemove');
});

function swclass(c){
    $('.' + c).removeClass('red');
    $(this).addClass('blue');
}
.red{
  color:red;
}
.blue{
   color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="itemove red">Hello</p>
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
0

Try following

$(document).on('click', '.itemove', function() {
    swclass.bind(this)('itemoveact');
});

function swclass(c){
    $('.' + c).removeClass(c);
    $(this).addClass(c);
}

swclass.bind(this)('itemoveact');

bind function will apply the scope of your '.itemove' to swclass function and then make a call.

This read would help What is the scope of variables in JavaScript?

0

You can jump through some hoops to change the value of this, but it’s easier and simpler to pass it as an argument:

$(document).on('click', '.itemove', function() {
    swclass('itemoveact', this);
});

function swclass(c, addTo){
    $('.' + c).removeClass(c);
    $(addTo).addClass(c);
}
Ben West
  • 4,398
  • 1
  • 16
  • 16