1

Here is an example of code what I am trying to do.

This is not working:

function fnSelectableDiv(){
  $('.selectableDiv').removeClass('selected-div');
  $(this).addClass('selected-div');
}

$('.selectableDiv').click(function () {
  fnSelectableDiv()
});

If i do as mentioned below, things will work but I am trying to figure out how to make above code work:

$('.selectableDiv').click(function () {
  $('.selectableDiv').removeClass('selected-div');
  $(this).addClass('selected-div');
});

CSS

.selectableDiv{width: 100px; height: 20px; border: 2px solid #333}
.selected-div{background-color:red)

HTML

<div class="selectableDiv"></div>
<div class="selectableDiv"></div>
Oleksandr T.
  • 69,412
  • 16
  • 152
  • 136
Syed
  • 11,612
  • 10
  • 82
  • 122

3 Answers3

3

There are couple ways how you can solve it

Use .call() to set this in your function:

function fnSelectableDiv(){
  $('.selectableDiv').removeClass('selected-div');
  $(this).addClass('selected-div');
}

$('.selectableDiv').click(function () {
  fnSelectableDiv.call(this); // set context for fnSelectableDiv.
});

Pass the value of this as an argument to this function:

function fnSelectableDiv(el){
  $('.selectableDiv').removeClass('selected-div');
  $(el).addClass('selected-div');
}

$('.selectableDiv').click(function () {
  fnSelectableDiv(this); // pass this as argument 
});
jfriend00
  • 580,699
  • 78
  • 809
  • 825
Oleksandr T.
  • 69,412
  • 16
  • 152
  • 136
  • 1
    use `.call($(this))` instead... as this.addClass() won't work but $(this).addClass() works... – Bhojendra Rauniyar Feb 04 '15 at 06:36
  • 1
    @BhojendraNepal - why? There's no advantage to passing `$(this)` instead of passing `this`. In fact, your method makes more work for the caller and less common code in the function. – jfriend00 Feb 04 '15 at 06:37
  • will this.addClass() work then? – Bhojendra Rauniyar Feb 04 '15 at 06:38
  • @BhojendraNepal - I don't know what you're asking. This answer does not use `this.addClass()` anywhere. It uses either `$(this).addClass()` or `$(el).addClass()` - both of which will work in their context. – jfriend00 Feb 04 '15 at 06:40
1

Pass the arguement to 'fnSelectableDiv(obj)'

function fnSelectableDiv(obj){
  $('.selectableDiv').removeClass('selected-div');
  $(obj).addClass('selected-div');
}

$('.selectableDiv').click(function () {
  fnSelectableDiv(this); // pass this as argument 
});
Dadaso Zanzane
  • 5,229
  • 1
  • 21
  • 22
0

Do like this:

function fnSelectableDiv(elem){//pass a parameter for element
  $('.selectableDiv').removeClass('selected-div');
  elem.addClass('selected-div');
}

$('.selectableDiv').click(function () {
  fnSelectableDiv($(this))//use element as $(this)
});
Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187