Nathanael
Nathanael

Reputation: 7163

Can you use a jQuery handler as .on()'s selector?

Is it possible to use a jQuery handler $(...) as the selector for .on()? The code snippet below demonstrates my point: how do I make the circle turn blue if I don't have a plaintext representation of my selector, but do have a handler?

// This works.
$(document).on('click', '#wow', function()
{
    $(this).css('background-color', '#FF0000');
});

// This doesn't work, but I need it to!
var context = $('#wow');
$(document).on('click', context, function()
{
    $(this).css('background-color', '#0000FF');
});
#wow
{
  background-color: #CCC;
  border-radius: 100px;
  height: 100px;
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wow"></div>

Upvotes: 0

Views: 41

Answers (4)

charlietfl
charlietfl

Reputation: 171669

If $('#wow') exists when you run var context = $('#wow'); then use that existing object directly

var context = $('#wow');

context.on('click', function()
{
    $(this).css('background-color', '#0000FF');
});
#wow
{
  background-color: #CCC;
  border-radius: 100px;
  height: 100px;
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wow"></div>

Upvotes: 1

Rudie
Rudie

Reputation: 53831

No, but you can give the element a random class and use that:

var context = $('#wow');
var cls = 'x' + String(Math.random()).substr(2);
context.addClass(cls);
$(document).on('click', '.' + cls, function() {});

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370779

Assuming the element you want is the first in the collection (eg. you selected an id), you can select the first element in the collection and then compare the event.target to the element:

const context = $('#wow');
const elm = context.get(0);
$(document).on('click', ({ target }) => {
  if (elm.contains(target)) $(elm).css('background-color', '#0000FF');
});
#wow
{
  background-color: #CCC;
  border-radius: 100px;
  height: 100px;
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wow"></div>

Upvotes: 0

Taplar
Taplar

Reputation: 24965

No. The point of the second parameter of a delegate event handler is a selector to match against the elements the event originates from in the future. Trying to use existing elements as the second parameter does not match the purpose of a delegate event handler.

For more reading: http://learn.jquery.com/events/event-delegation/

Otherwise just use a normal event handler.

$('#wow').on('click', function() {
    $(this).css('background-color', '#FF0000');
});

Upvotes: 1

Related Questions