Close Modal using CSS only

房东的猫 提交于 2019-12-05 10:30:37

If you don't want to use JQuery to close the modal when you click on the ok button you could do something similar to the following code with plain JavaScript. You will have to assign an index to the selector to get it to work.

    //begin click event
    document.getElementById("ok").addEventListener("click",function(event){


    /* Hide the element with a class name of modal.
       note:If there is more than one element with the class name
       modal then this code will only select the first one in the
       collection of elements 
    */

    document.getElementsByClassName("modal")[0].style.display = "none";


       });//end click event

Based on your js code, you are injecting modal elements into the dom document.getElementById("alert").innerHTML = 'modal stuff' if you want to get rid of it, the most simplest way, use an empty string like this: document.getElementById("alert").innerHTML = ''

CSS way would be something like display: none.

The proper way you should close it, by invoking javascript close function, which would remove modal and clean up after itself (so old code is not there anymore). This method depends on the types of modals and what you want to achieve.

I don't believe there is a css only way to close/hide the modal upon clicking the OK button. However, it should be very easy to close with plain Javascript. Depending on whether you want to hide the modal (but keep it in the DOM), or actually remove the modal elements you could implement it like this.

 // To hide, run this inside a click callback
 document.getElementById('modal').classList.push('hide');

 .hide {
   display: hidden;
 }



 // And to remove
 var modal = document.getElementById('modal');
 modal.parentNode.removeChild(modal);

Also you would have to add a #modal id to your modal, instead of just a class (unless you want to use document.getElementsByClassName)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!