Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $(this) not working when inside a function

I have this simple function that copies some html, and places it in another div. If I put the code for the function in the click event it works fine, but when I move it into a function (to be used in multiple places) it no longer works. Do you know why this is?

If I console.log($(this)); in the function it returns the window element.

 function addHTMLtoComponent () {
        var wrapper = $(this).closest(".wrapper");
        var component = $(wrapper).find(".component");
        var componentCodeHolder = $(wrapper).find('.target');   

         $(componentCodeHolder).text(component.html())
      //console.log($(this));
 }

 $(".js_show_html").click(function () {
     addHTMLtoComponent();
 });

codepen here - http://codepen.io/ashconnolly/pen/ebe7a5a45f2c5bbe58734411b03e180e

Should i be referencing $(this) in a different way?

like image 790
Ash Avatar asked Jan 31 '26 21:01

Ash


2 Answers

Regarding other answers, i need to put the easiest one:

$(".js_show_html").click(addHTMLtoComponent);
like image 178
A. Wolff Avatar answered Feb 02 '26 10:02

A. Wolff


since you called the function manually the function doesn't know the "this" context, therefore it reverted back to use the window object.

$(".js_show_html").click(function () {
     addHTMLtoComponent();
 });

// Change to this

$(".js_show_html").click(function () {
     // the call function allows you to call the function with the specific context
     addHTMLtoComponent.call(this);
 });

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

like image 32
Du D. Avatar answered Feb 02 '26 10:02

Du D.