user2268430
user2268430

Reputation: 23

addClass doesnt add the class to the element

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

                });
            }

Upvotes: 0

Views: 40

Answers (2)

Qonvex620
Qonvex620

Reputation: 3972

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.

Upvotes: 0

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14198

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>

Upvotes: 1

Related Questions