Jacki
Jacki

Reputation: 672

Launch event on click of element but on things inside element

Hello I made drawer which appears when you click on it and then expands it's width, after second click, it back to it's minimalized form, inside this drawer I have table with checkboxes etc which I will use later to filter things. Thing is that if I click on checkbox inside the table, drawer is hiding. How to do it that event which allow for toggling of width of drawer would work only if I click on it except place where is table? As far as I know it should do something with stopPropagation but somehow I was unabled to implement it in working form.

<div class="filter_drawer" onclick="show_stat()">
        <Table class="stat_table">
            ...some content
        </Table>
    </div>

function show_stat() {
    event.stopPropagation()
    var stats = document.querySelector('.filter_drawer')
    var table = stats.querySelector('.stat_table')
    var panels = document.querySelector('.main_container')

    stats.classList.toggle('expanded_stat')
    table.classList.toggle('show')
    panels.classList.toggle('expanded_stat_panel')

}

Upvotes: 0

Views: 31

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370889

Attach the listener to the element properly using Javascript instead, and then you can check if the event.target is the .filter_drawer element. If so, then it was a click directly on the element, and not one of its descendants:

document.querySelector('.filter_drawer').addEventListener('click', (e) => {
  if (e.target.matches('.filter_drawer')) {
    showStat();
  }
});

(If the click was on a descendant element, and not the filter_drawer itself, then the e.target test won't match)

No need for stopPropagation.

Upvotes: 1

Related Questions