0

I'm trying to use the Javascript module pattern for the first time to organize my code. I understand the how "this" works here but cannot figure out how $(this) works. For example, the code below, $(this).addClass('video-active'); in "chooseVideo" function, I want to apply addClass only for the clicked element. But it does not work. Could anybody give me some advice? Thank you!

;(function() {
   'use strict';
   if (typeof window.jQuery !== 'function') {
     return;
   }
   var $ = jQuery;

   var video = {
     init: function() {
       this.cacheDom();
       this.bindEvents();
       this.render();
     },
     cacheDom: function() {
       this.$el = $('#videoWrap');
       this.$button = this.$el.find('.video');
     },
     render: function() {

     },
     bindEvents: function() {
       this.$button.bind('click', this.chooseVideo.bind(this));
     },
     chooseVideo: function(e) {
       e.preventDefault ? e.preventDefault() : e.returnValue = false;
       this.$button.removeClass('video-active');
       $(this).addClass('video-active');
     }
   };

   video.init();

})();
5
  • $(this).addClass('video-active'); should not work Commented Mar 22, 2016 at 3:24
  • $(this) is the standard way of wrapping something like a DOM element in the jQuery handler. Commented Mar 22, 2016 at 3:25
  • @tadman But this is not a DOM element Commented Mar 22, 2016 at 3:26
  • It better be if you're calling addClass on it. Remember this changes wildly from function to function. Commented Mar 22, 2016 at 3:27
  • And you do not know who you are talking too... lol Commented Mar 22, 2016 at 3:28

1 Answer 1

2

when you use bind, you are changing the context of this

So you will need to use the event object to get what was clicked.

chooseVideo: function(e) {
   e.preventDefault ? e.preventDefault() : e.returnValue = false;
   this.$button.removeClass('video-active');
   $(e.target).addClass('video-active');
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I was struggling this issue for a few hours! You save my day! Really appreciate it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.