0

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.

1 Answer 1

2

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');
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it works, but maybe another question that the event is triggered forever .How to stop the event once it is triggered once ?
Follow-on question has been correctly added as a new question: stackoverflow.com/questions/58804192/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.