Kenzo
Kenzo

Reputation: 1837

How to trigger data-click event in javascript

In my Html i have a sidebar with an anchor on which i can click to expand/collapse the sidebar, however i would like to achieve with javascript. Here is what i have tried but i am not getting the desired results.

Html file:

<!-- begin sidebar minify button -->
<a href="javascript:;" class="sidebar-minify-btn" data-click="sidebar-minify">
   <i class="fa fa-angle-left"></i>
</a>
<!-- end sidebar minify button -->

js file :

  window.onresize = function()
  {
     const width = window.innerWidth;
     if(width <= 800)
     {
       $('a[data-click="sidebar-minify"]').click(function(event)
       {
          console.log('sidebar clicked');
       }
     }
  }

Basically what i want to achieve is to detect if the browser window width has changed to less than 800px and then trigger the click event on the sidebar. I would appreciate any help.

Upvotes: 0

Views: 1577

Answers (1)

Jamesypoo
Jamesypoo

Reputation: 110

To be clear, jQuery click() is used to attach an event handler to the element. Looks like you are doing this correctly.

What you're looking for is jQuery trigger(), with which you can trigger an event. In your case, try

$('a[data-click="sidebar-minify"]').trigger('click');

Upvotes: 2

Related Questions