0

I want to add a class .filter_open to my element id #block_filters when click in #filter-button a element so here is my HTML:

<a id="filter-button" >Show filters</a>
<div class="block_content" id="block_filters" >


</div>

Here my .js

function open_filters() {
  var f_toggle = $('#filter-button');
  var f_content = $('#block_filters');
  f_toggle.on('click', function(e) {
    f_content.addClass('filter_open');
    e.stopPropagation();
    e.preventDefault();
  });

}

But It's not working, I can't find the reason.

Thanks for your help

Edit:

I am also testing this way, but no luck

$(document).ready(function () 
            {
                $('#filter-button').click(function () {
                    $('#block_filters').addClass('filter_open');

                });
            }
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56

2 Answers2

1

You can try this way. Read the link below to have a better understanding

Event binding on dynamically created elements?

$(document).ready(function() { open_filters(); });

function open_filters() {
  var f_toggle = $(document).find('#filter-button');
  var f_content = $(document).find('#block_filters');
  
  f_toggle.on('click', function(e) {
    f_content.addClass('filter_open');
    e.stopPropagation();
    e.preventDefault();
  });

}
.filter_open{
 background-color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="filter-button" >Show filters</a>
<div class="block_content" id="block_filters" >Content</div>
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
  • WOW! That function works like a charm! Thanks so much! Ive been trying to find a solution for hours. Now Im going to read the link to better understanding it, because now I need to add a .removeClass() button. – user2268430 Jan 21 '20 at 02:06
0

Just add preventDefault in your script to avoid the browser to refresh, see code below

$('#filter-button').click(function (e) {
    e.preventDefault()
    $('#block_filters').addClass('filter_open');

});

Make sure you have imported jquery script in your head tag

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

basically, you had already added a class but since the page reload then it will set again its class to default.

Qonvex620
  • 3,819
  • 1
  • 8
  • 15