最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Opening modal from function in pure javascript - Stack Overflow

programmeradmin7浏览0评论

I want to open a modal with a function in pure javascript (not jquery).

Component from where i am calling function:

<div class="col-sm-5 offset-sm-5" 
    style={{ bottom: "60px", marginBottom: "20px", marginTop: "23px" }}>
    <button class="btn btn-primary btn-sm" onClick={this.handleSubmit.bind(this)}>Save</button>
</div>

Function code:

handleSubmit=()=>{
    document.getElementById('exchangehouse').style.display = "block"    
}

Modal code:

<div class="modal fade" id="exchangehouse" tabindex="-1" role="dialog" 
    aria-labelledby="exampleModalLongTitle" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

Thanks

I want to open a modal with a function in pure javascript (not jquery).

Component from where i am calling function:

<div class="col-sm-5 offset-sm-5" 
    style={{ bottom: "60px", marginBottom: "20px", marginTop: "23px" }}>
    <button class="btn btn-primary btn-sm" onClick={this.handleSubmit.bind(this)}>Save</button>
</div>

Function code:

handleSubmit=()=>{
    document.getElementById('exchangehouse').style.display = "block"    
}

Modal code:

<div class="modal fade" id="exchangehouse" tabindex="-1" role="dialog" 
    aria-labelledby="exampleModalLongTitle" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

Thanks

Share Improve this question edited Aug 9, 2018 at 5:51 wazz 5,0685 gold badges22 silver badges36 bronze badges asked Aug 9, 2018 at 5:45 Sachin L ShettySachin L Shetty 311 gold badge1 silver badge3 bronze badges 3
  • 1 bootstrap uses jQuery, what is the purpose for opening it using pure javascript? – Julian Paolo Dayag Commented Aug 9, 2018 at 5:48
  • 1 Same as @JulianPaoloDayag said, bootstrap uses jquery. And with react, why do you want to open like this, you can toggle a state variable and then switch the modal Show/Hide with the reference of that modal. Why you want to do it like this? – Abin Thaha Commented Aug 9, 2018 at 5:51
  • @JulianPaoloDayag It is possible . Me Also I want to use modal without javascript because I am doing a chalenge that restict the use of jquery – GNETO DOMINIQUE Commented Oct 3, 2021 at 9:10
Add a ment  | 

4 Answers 4

Reset to default 9

Are you searching for this?

// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
}

/* The Close Button */
.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Your Contents</p>
  </div>

</div>

Here is a modern, pure ES6 implementation of a modal window.

I also included some simple open/close hooks.

class ModalWindow {
  constructor(options) {
    this.opts = Object.assign({}, ModalWindow._defaultOptions, options)
    this.modal = document.querySelector(this.opts.selector)
    this.initialize()
    this.addEventHandlers()
    this.afterRender()
  }
  initialize() {
    if (this.opts.headerText) {
      this.query('.md-dialog-header-text').textContent = this.opts.headerText
    }
    if (this.opts.htmlContent) {
      this.query('.md-dialog-content').innerHTML = this.opts.htmlContent
    } else if (this.opts.textContent) {
      this.query('.md-dialog-content').textContent = this.opts.textContent
    }
    if (this.opts.theme) {
      this.modal.classList.add(`md-theme-${this.opts.theme}`)
    }
  }
  addEventHandlers() {
    this.query('.md-dialog-header-close-btn').addEventListener('click', (e) => {
      this.setVisible(false)
    })
    if (this.opts.mode !== 'modal') {
      this.modal.addEventListener('click', (e) => {
        if (e.target === this.modal) {
          this.setVisible(false)
        }
      })
    }
  }
  afterRender() {
    if (this.opts.show === true) {
      this.setVisible(true);
    }
  }
  setVisible(visible) {
    this.modal.classList.toggle('md-dialog-visible', visible)
    if (visible) {
       this.onOpen() // class method override or callback (below)
       if (typeof this.opts.onOpen === 'function') {
        this.opts.onOpen(this.modal)
       }
    } else {
      this.onClose() // class method override or callback (below)
      if (typeof this.opts.onClose === 'function') {
        this.opts.onClose(this.modal)
       }
    }
  }
  query(childSelector) {
    return this.modal.querySelector(childSelector)
  }
  // Example hooks
  onOpen() { }
  onClose() { } 
}
ModalWindow._defaultOptions = {
  selector: '.md-dialog',
  show: false,
  mode: 'modal'
}

class MyCustomModalWindow extends ModalWindow {
  constructor(options) {
    super(options)
  }
  onOpen() {
    console.log('Opened!') // or you can use options.onOpen
  }
  onClose() {
    console.log('Closed!') // or you can use options.onClose
  }
}

let modal = new MyCustomModalWindow({
  show: true, // Show the modal on creation
  mode: null, // Disable modal mode, allow click outside to close
  headerText: 'Hello World!',
  htmlContent: '<p>This is an example of the popup.</p>',
  theme : 'dark',
  onClose : (self) => {
    console.log('Another close hook...')
  }
})
document.querySelector('#show-modal-btn').addEventListener('click', (e) => {
  modal.setVisible(true)
})
.md-dialog {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.4);
}
.md-dialog.md-dialog-visible {
  display: block;
}
.md-dialog .md-dialog-window {
  border: 1px solid #888;
  background-color: #fefefe;
  width: 80%;
  margin: 10% auto;
}
.md-dialog .md-dialog-header {
  position: relative;
  width: calc(100% - 0.5em);
  height: 1.667em;
  font-weight: bold;
  font-size: 1.33em;
  line-height: 1.667em;
  padding: 0.125em 0.25em;
  background-color: #DDD;
}
.md-dialog .md-dialog-header-close-btn {
  position: absolute;
  font-weight: bold;
  top: 0;
  right: 0;
  width: 0.875em;
  height: 0.875em;
  line-height: 1em;
  padding: 0.1em;
  color: #7F7F7F;
}
.md-dialog .md-dialog-header-close-btn:before {
  content: '\2715';
}
.md-dialog .md-dialog-header-close-btn:hover,
.md-dialog .md-dialog-header-close-btn:focus {
  color: #FFF;
  text-decoration: none;
  cursor: pointer;
  background: #F00;
}
.md-dialog .md-dialog-content {
  width: 100%;
  padding: 0.25em;
}


/** Example Dark Theme */
.md-theme-dark.md-dialog {
  background-color: rgba(0, 0, 0, 0.8);
}
.md-theme-dark.md-dialog .md-dialog-window {
  border: 1px solid #666;
  background-color: #111;
  color: #EEE;
}
.md-theme-dark.md-dialog .md-dialog-header {
  background-color: #000;
}
.md-theme-dark.md-dialog .md-dialog-header-close-btn {}
.md-theme-dark.md-dialog .md-dialog-header-close-btn:hover,
.md-theme-dark.md-dialog .md-dialog-header-close-btn:focus {}
.md-theme-dark.md-dialog .md-dialog-content {}
<link href="https://cdnjs.cloudflare./ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet" />
<button id="show-modal-btn">Open Modal</button>

<div id="myModal" class="md-dialog">
  <div class="md-dialog-window">
    <div class="md-dialog-header">
      <div class="md-dialog-header-close-btn"></div>
      <div class="md-dialog-header-text">$header</div>
    </div>
    <div class="md-dialog-content">$content</div>
  </div>
</div>

In Bootstrap 5 (Beta 1) this gets as simple as this:

Your button (having onClick function call):

<button type="button" class="btn btn-primary" onclick='openModal()'>
        Launch demo modal</button>

Your Modal:

<div class="modal fade" id="myModal" tabindex="-1"
        aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"
                        aria-label="Close"></button>
                </div>
                <div class="modal-body">...</div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary"
                        data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>

And finally, the "pure" java script function:

<script type="text/javascript"> 
function openModal() {
  var myModal = new bootstrap.Modal(document.getElementById('myModal'), {  keyboard: false });
  myModal.show();
}
</script>

well usually the option of modal for visibility is managed in state as boolean type.

you have to change the value of visibility as true(which is open) or false(and close), if there is no function that make visibility as false then you can't close the modal.

which mean is you need to use 'function' to change the 'value of visibility' that where in 'state' to control the modal view.

in react way.

view =( open modal )==> action === ( visibility) ==> state ===( change the value)===> view

and also your question is very abstractive.

anyway i hope that my answer can help you.

发布评论

评论列表(0)

  1. 暂无评论