Search code examples
javascriptjqueryaddeventlistener

addEventListener not working. Help me to correct an JS


why that is not working ?

var headerBanner= $(".header-banner");
var closeBtn = $('closeBtn');

closeBtn.addEventListener('click', function () {
  headerBanner.classList.add('IsClose');
}, false);

.closeBtn {
  position: relative;
  display: inline-block;
  width: 20px;
  height: 20px;
  overflow: hidden;
  opacity: 0.8; 
  float: right;
  cursor: pointer;

}


I want to make custom button to close.
in f12 can't see "IsClose". Do I make any mistake in js ?


Solution

  • There are many errors in your code, this is I assume.

    First, you are using jQuery to select elements, but then trying to use the addEventListener which is a native js method. In jQuery, you should use the on method to attach event handlers. Then, you are using $('closeBtn') to select your close button. This is INCORRECT because it's trying to select closeBtn which doesn't exist. If closeBtn is a class, you should use $('.closeBtn') instead. Lastly, you are trying to add a class to headerBanner using classList.add, but headerBanner is a jQuery object, not a DOM element, so you should use the addClass method.

    Sample workaround;

    $(document).ready(function() {
     var headerBanner = $(".header-banner");
     var closeBtn = $('.closeBtn');
    
     closeBtn.on('click', function () {
       headerBanner.addClass('IsClose');
     });
    });
    .header-banner {
     width: 100%;
     height: 100px;
     background-color: #f00;
    }
    
    .closeBtn {
     position: relative;
     display: inline-block;
     width: 20px;
     height: 20px;
     overflow: hidden;
     opacity: 0.8; 
     float: right;
     cursor: pointer;
    }
    
    .IsClose {
     display: none;
    }
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <div class="header-banner">
     <div class="closeBtn">X</div>
    </div>