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');

                });
            }
2
  • Where is open_filters called? You need to call it, then click on the toggle element Commented Jan 21, 2020 at 1:19
  • I have code$( document ).ready(function() { open_filters(); }); But no luck Commented Jan 21, 2020 at 1:33

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.