-1

The following code works. It creates a little dropdown menu (HTML select element) that changes the color of "MY TEST TEXT".

<script src="jquery-2.0.3.min.js"></script>

<p id="color-target">MY TEST TEXT</p>

<label for="test-menu">My Menu Label</label>
<select id="test-menu">
    <option>red
    <option>green
    <option>blue
    <option>magenta
</select>

<script>
$("#test-menu").on("change", function(e) {
    $("#color-target").css("color", $(this).find("option:selected").val());
});
</script>

I wrote this code in various ways as part of a test and was surprised that it worked in this form. The mystery for me is, Why does "$(this)" refer to the "select#test-menu" element instead of the "p#color-target" element? I thought that $(this) used within the method of an object referred to the containing object, but in this code, $(this) is used within the .css() method of Object P which itself is used within an anonymous function, which is then used within the .on() method of Object S, so $(this) is simultaneously used within multiple functions. I assumed that in such a case $(this) would refer to the innermost containing object, p#color-target, but here it doesn't.

Why not?

(I'm tagging this with both jQuery and JavaScript, because I don't know whether the answer applies to jQuery's "$(this)" specifically or more generally to JavaScript's "this".)

Glen
  • 524
  • 2
  • 4
  • 12
  • I recommend to read [**the jQuery tutorial**](http://learn.jquery.com/events/event-basics/), it may also answer other questions: *"In addition to the event object, the event handling function also has access to the DOM element that the handler was bound to via the keyword `this`."* – Felix Kling Aug 08 '14 at 07:18

1 Answers1

0

Because you are selecting "#test-menu" as in $("#test-menu").on(... and within the function $(this) refers to #test-menu element

Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187