Patrick McDermott Patrick McDermott - 1 year ago 61
HTML Question

Issue with document on 'load' event listener

First issue

My script runs fine when it listens for a

event on the element with the id
. Instead of a
event, I want the script to fire up on
event and get rid of the
button. But I have tried it and it isn't working. Any idea why it isn't firing up the modal script?

Second issue

The modal window should close when the user clicks the close button, but it doesn't. I have added
to all functions and they are fired up every time I click close which shouldn't happen. Any idea why it isn't closing?

var $content = $('#welcome-modal').detach();

$(document).on('load', function() {{
content: $content,
width: 500

var modal = (function() {
var $window = $(window); //store the window object
var $modal = $('<div class="modal-window">'); //create markup for modal
var $content = $('<div class="modal-content">');
var $close = $('<button role="button" class="modal-close">close</button>');

$modal.append($content, $close); //append content and close button

$close.on('click', function(e) { //if user clicks on close button
e.preventDefault(); //prevent default behaviour
modal.close(); //close modal


return { //add code to modal
center: function() {
var top = Math.max($window.height() - $modal.outerHeight(), 0) / 2; //calculate distance from top
var left = Math.max($window.width() - $modal.outerWidth(), 0) / 2; //calculate distance from left

top: top + $window.scrollTop(), //apply css positioning to the modal
left: left + $window.scrollLeft()
open: function(settings) {

$modal.css({ //removed height so it's auto
width: settings.width || 'auto'
close: function() {
$content.empty(); //Remove all child nodes of the set of matched elements from the DOM.

.modal-window {
position: absolute;
z-index: 10000;
background: #fff;
padding: 1.5em;
clear: both;
overflow: hidden;

.modal-content {
border: 0;

#share span {
cursor: pointer;

<script src=""></script>
<div id="share">
<span class="fa fa-heart fa-3x"></span>
<div id="welcome-modal">
<h4>This is jibber title</h4>
<p>A load of jibber jabber</p>

Answer Source

Your first issue is that you have a document.load event handler being registered inside of a document.ready function that is self-invoking!

// When you pass a function to JQuery, that function is automatically
// executed when the DOM is ready. No need to self-invoke it.
  var $content = $('#welcome-modal').detach();

    // Since this code is already running when the DOM is ready
    // there is no need to make this code the callback for document.load{
        content: $content,
        width: 500          
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download