1

I have a variable that's supposed to store the data-filter of what has just been clicked. It only works inside one of my click events though, and stops working when it is moved outside of that event. I want to make it global so that I can access it anytime, but I don't understand jQuery well enough to know what the issue is.

$(document).ready(function () {
  var filterValue = $(this).attr('data-filter');
  //Function Doesn't work when var filterValue is located here.

  $('nav').on('click', 'a', function () {
    //This function works when var filterValue is located here.

    $('nav').find('.is-checked').removeClass('is-checked');
    $(this).addClass('is-checked');
    if ($(this).data('filter') === 'home') {
      $('main').find('.dim').removeClass('dim', 500);
    } else {
      $('.cell')
        .not('.' + filterValue)
        .addClass('dim', 500);
      $('main')
        .find('.' + filterValue)
        .removeClass('dim', 500);
    }
  });
  $('main').on('click', filterValue, function () {
    //This function does not work when var filterValue is located here.

    console.log(filterValue);
  });
});
Nick is tired
  • 6,860
  • 20
  • 39
  • 51
jdeut
  • 19
  • 4
  • 2
    You cannot use the `this` keyword in the global domain. You should use the `this` keyword in context. – Sercan Jan 09 '22 at 22:26
  • Start https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – user2864740 Jan 09 '22 at 22:36
  • Does this answer your question? [How to access the correct \`this\` inside a callback](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – user2864740 Jan 09 '22 at 22:37
  • Please provide a Minimal, Reproducible Example: https://stackoverflow.com/help/minimal-reproducible-example – Twisty Jan 12 '22 at 17:13
  • I ended up changing my code from this to something else. This does help me understand a bit more how jQuery works, thank you! – jdeut Jan 13 '22 at 19:50

1 Answers1

1

Inside of the function, this is in a different scope (Local). If you want to use the same scope, you should assign the first scope to a new variable called that or something else.

function someFunc() {
    var that = this;
    something.on("click", function() {
        console.log(that);
    });
};
Rodrigo Soares
  • 347
  • 5
  • 10
  • What you answered is correct yet it does not answer nor address the issues with OP's code. – Twisty Jan 12 '22 at 17:14
  • 1
    I ended up changing my code from this to something else. This does help me understand a bit more how jQuery works, thank you! – jdeut Jan 13 '22 at 19:50