0

I have a file "A" with

$('.myClass').mouseover(function() {
    myFunction();
});

and a file "B" with

function myFunction() {
    $(this).hide();
};

It doesn't work because $(this) is undefined.

Is there a way I can pass the $(this) selector across multiple files?

3 Answers3

0

The quickest and easiest solution I can think of:

$('.myClass').mouseover(function(e) {
    myFunction(e.target);
});

function myFunction(element) {
    $(element).hide();
};

Since this inside myFunction() would return the Window object, I'd pass the element gathered from the jQuery event (e.target) and place that inside a jQuery function inside myFunction(). With this you can manipulate the exact element the event was triggered on.

SneakyLenny
  • 316
  • 2
  • 4
0

file A

$('.myClass').mouseover(function() {
    myFunction($(this));
});

file B

function myFunction(element) {
    element.hide();
};
ibrahim s
  • 179
  • 6
0

You can either reference the method directly or use apply() or call()

function myFunction() {
    $(this).toggleClass('active');
};


function myFunction2() {
    $(this).toggleClass('foo');
};

$('.myClass').mouseover(myFunction);


$('.myClass').mouseover(function () {
  myFunction2.apply(this);
});
.active { color: red;}
.foo { background-color: yellow;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="myClass">1</div>
<div class="myClass">2</div>
<div class="myClass">3</div>
epascarello
  • 185,306
  • 18
  • 175
  • 214