Clean way to close dropdown list when clicking outside












0















I have a button that opens a dropdown list when clicking on.



I want to close this list when clicking outside the button. So I used a HostListener like this:



@HostListener('click', ['$event.target'])
toggleDropdown(element) {
const clickOnDropdownButton = (): boolean => {
const buttonChildsClasses = ['button is-primary tog-button', 'dropdown-label', 'tog-icon tog-icon-arrow-down', 'icon is-small'];
return buttonChildsClasses.indexOf(element.className) !== -1;
};
if (this.dropDownActive) {
this.dropDownActive = false;
} else if (!this.dropDownActive && clickOnDropdownButton()) {
this.dropDownActive = true;
}
}


This works but the use of a possible childs array is not clean at all in my opinion.



Indeed, the problem with my button is that it is composed of several HTML elements, my button isn't just a button tag.



I thought of having a HTML element on top of those other elements using position: absolute but I'm not sure if it's cleaner.



Any thoughts on this problem ?










share|improve this question

























  • I strongly recommend you use Angular CDK to implement dropdown component, its really very nice! you can see Example in my github github.com/100cm/at-ui-angular/blob/master/src/app/components/…

    – junk
    Nov 13 '18 at 9:58











  • the way i solved this was to add a click handler on the parent element of the dropdown (containing the dropdown opener button and the options list) and calling event.stopPropagation() there

    – schellmax
    Nov 13 '18 at 10:05











  • You can use a simple Jquery script and include that on the pages with dropdowns, nice thing is you can reuse this for all dropdowns all around your site. Maybe not the best option, but it is a simple option.

    – Roboneter
    Nov 14 '18 at 13:33
















0















I have a button that opens a dropdown list when clicking on.



I want to close this list when clicking outside the button. So I used a HostListener like this:



@HostListener('click', ['$event.target'])
toggleDropdown(element) {
const clickOnDropdownButton = (): boolean => {
const buttonChildsClasses = ['button is-primary tog-button', 'dropdown-label', 'tog-icon tog-icon-arrow-down', 'icon is-small'];
return buttonChildsClasses.indexOf(element.className) !== -1;
};
if (this.dropDownActive) {
this.dropDownActive = false;
} else if (!this.dropDownActive && clickOnDropdownButton()) {
this.dropDownActive = true;
}
}


This works but the use of a possible childs array is not clean at all in my opinion.



Indeed, the problem with my button is that it is composed of several HTML elements, my button isn't just a button tag.



I thought of having a HTML element on top of those other elements using position: absolute but I'm not sure if it's cleaner.



Any thoughts on this problem ?










share|improve this question

























  • I strongly recommend you use Angular CDK to implement dropdown component, its really very nice! you can see Example in my github github.com/100cm/at-ui-angular/blob/master/src/app/components/…

    – junk
    Nov 13 '18 at 9:58











  • the way i solved this was to add a click handler on the parent element of the dropdown (containing the dropdown opener button and the options list) and calling event.stopPropagation() there

    – schellmax
    Nov 13 '18 at 10:05











  • You can use a simple Jquery script and include that on the pages with dropdowns, nice thing is you can reuse this for all dropdowns all around your site. Maybe not the best option, but it is a simple option.

    – Roboneter
    Nov 14 '18 at 13:33














0












0








0








I have a button that opens a dropdown list when clicking on.



I want to close this list when clicking outside the button. So I used a HostListener like this:



@HostListener('click', ['$event.target'])
toggleDropdown(element) {
const clickOnDropdownButton = (): boolean => {
const buttonChildsClasses = ['button is-primary tog-button', 'dropdown-label', 'tog-icon tog-icon-arrow-down', 'icon is-small'];
return buttonChildsClasses.indexOf(element.className) !== -1;
};
if (this.dropDownActive) {
this.dropDownActive = false;
} else if (!this.dropDownActive && clickOnDropdownButton()) {
this.dropDownActive = true;
}
}


This works but the use of a possible childs array is not clean at all in my opinion.



Indeed, the problem with my button is that it is composed of several HTML elements, my button isn't just a button tag.



I thought of having a HTML element on top of those other elements using position: absolute but I'm not sure if it's cleaner.



Any thoughts on this problem ?










share|improve this question
















I have a button that opens a dropdown list when clicking on.



I want to close this list when clicking outside the button. So I used a HostListener like this:



@HostListener('click', ['$event.target'])
toggleDropdown(element) {
const clickOnDropdownButton = (): boolean => {
const buttonChildsClasses = ['button is-primary tog-button', 'dropdown-label', 'tog-icon tog-icon-arrow-down', 'icon is-small'];
return buttonChildsClasses.indexOf(element.className) !== -1;
};
if (this.dropDownActive) {
this.dropDownActive = false;
} else if (!this.dropDownActive && clickOnDropdownButton()) {
this.dropDownActive = true;
}
}


This works but the use of a possible childs array is not clean at all in my opinion.



Indeed, the problem with my button is that it is composed of several HTML elements, my button isn't just a button tag.



I thought of having a HTML element on top of those other elements using position: absolute but I'm not sure if it's cleaner.



Any thoughts on this problem ?







javascript html angular






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 10:27









Krupesh Kotecha

2,05011134




2,05011134










asked Nov 13 '18 at 9:49









Baptiste ArnaudBaptiste Arnaud

7241726




7241726













  • I strongly recommend you use Angular CDK to implement dropdown component, its really very nice! you can see Example in my github github.com/100cm/at-ui-angular/blob/master/src/app/components/…

    – junk
    Nov 13 '18 at 9:58











  • the way i solved this was to add a click handler on the parent element of the dropdown (containing the dropdown opener button and the options list) and calling event.stopPropagation() there

    – schellmax
    Nov 13 '18 at 10:05











  • You can use a simple Jquery script and include that on the pages with dropdowns, nice thing is you can reuse this for all dropdowns all around your site. Maybe not the best option, but it is a simple option.

    – Roboneter
    Nov 14 '18 at 13:33



















  • I strongly recommend you use Angular CDK to implement dropdown component, its really very nice! you can see Example in my github github.com/100cm/at-ui-angular/blob/master/src/app/components/…

    – junk
    Nov 13 '18 at 9:58











  • the way i solved this was to add a click handler on the parent element of the dropdown (containing the dropdown opener button and the options list) and calling event.stopPropagation() there

    – schellmax
    Nov 13 '18 at 10:05











  • You can use a simple Jquery script and include that on the pages with dropdowns, nice thing is you can reuse this for all dropdowns all around your site. Maybe not the best option, but it is a simple option.

    – Roboneter
    Nov 14 '18 at 13:33

















I strongly recommend you use Angular CDK to implement dropdown component, its really very nice! you can see Example in my github github.com/100cm/at-ui-angular/blob/master/src/app/components/…

– junk
Nov 13 '18 at 9:58





I strongly recommend you use Angular CDK to implement dropdown component, its really very nice! you can see Example in my github github.com/100cm/at-ui-angular/blob/master/src/app/components/…

– junk
Nov 13 '18 at 9:58













the way i solved this was to add a click handler on the parent element of the dropdown (containing the dropdown opener button and the options list) and calling event.stopPropagation() there

– schellmax
Nov 13 '18 at 10:05





the way i solved this was to add a click handler on the parent element of the dropdown (containing the dropdown opener button and the options list) and calling event.stopPropagation() there

– schellmax
Nov 13 '18 at 10:05













You can use a simple Jquery script and include that on the pages with dropdowns, nice thing is you can reuse this for all dropdowns all around your site. Maybe not the best option, but it is a simple option.

– Roboneter
Nov 14 '18 at 13:33





You can use a simple Jquery script and include that on the pages with dropdowns, nice thing is you can reuse this for all dropdowns all around your site. Maybe not the best option, but it is a simple option.

– Roboneter
Nov 14 '18 at 13:33












1 Answer
1






active

oldest

votes


















0














 //this is your dropdown list in html 
<div #dropdown> </div>

//this is your ts

@Component({
host: {'(document:click)': 'handleClick($event)',}
})


@ViewChild('dropdown', {read: ElementRef}) dropdown: ElementRef;


handleClick(event) {
var clickedComponent = event.target;
do {
if (clickedComponent !== this.dropdown.nativeElement) {
it's call when we click outside the dropdown list
}

while (clickedComponent);
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53278170%2fclean-way-to-close-dropdown-list-when-clicking-outside%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














     //this is your dropdown list in html 
    <div #dropdown> </div>

    //this is your ts

    @Component({
    host: {'(document:click)': 'handleClick($event)',}
    })


    @ViewChild('dropdown', {read: ElementRef}) dropdown: ElementRef;


    handleClick(event) {
    var clickedComponent = event.target;
    do {
    if (clickedComponent !== this.dropdown.nativeElement) {
    it's call when we click outside the dropdown list
    }

    while (clickedComponent);
    }





    share|improve this answer




























      0














       //this is your dropdown list in html 
      <div #dropdown> </div>

      //this is your ts

      @Component({
      host: {'(document:click)': 'handleClick($event)',}
      })


      @ViewChild('dropdown', {read: ElementRef}) dropdown: ElementRef;


      handleClick(event) {
      var clickedComponent = event.target;
      do {
      if (clickedComponent !== this.dropdown.nativeElement) {
      it's call when we click outside the dropdown list
      }

      while (clickedComponent);
      }





      share|improve this answer


























        0












        0








        0







         //this is your dropdown list in html 
        <div #dropdown> </div>

        //this is your ts

        @Component({
        host: {'(document:click)': 'handleClick($event)',}
        })


        @ViewChild('dropdown', {read: ElementRef}) dropdown: ElementRef;


        handleClick(event) {
        var clickedComponent = event.target;
        do {
        if (clickedComponent !== this.dropdown.nativeElement) {
        it's call when we click outside the dropdown list
        }

        while (clickedComponent);
        }





        share|improve this answer













         //this is your dropdown list in html 
        <div #dropdown> </div>

        //this is your ts

        @Component({
        host: {'(document:click)': 'handleClick($event)',}
        })


        @ViewChild('dropdown', {read: ElementRef}) dropdown: ElementRef;


        handleClick(event) {
        var clickedComponent = event.target;
        do {
        if (clickedComponent !== this.dropdown.nativeElement) {
        it's call when we click outside the dropdown list
        }

        while (clickedComponent);
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 13 '18 at 10:12









        Ayush SahuAyush Sahu

        13810




        13810






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53278170%2fclean-way-to-close-dropdown-list-when-clicking-outside%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Florida Star v. B. J. F.

            Danny Elfman

            Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues