Reputation: 21
Can someone help me, Im trying to get a Modal to load when the page does but having some serious issues about it.
<script>
$('#overlay').modal('show');
setTimeout(function() {
$('#overlay').modal('hide');
}, 5000);
</script>
</head>
<body>
<div class="modal fade" id="overlay">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>Context here</p>
</div>
</div>
</div>
</div>
Upvotes: 0
Views: 2711
Reputation: 7523
Two issues:
One .. You're not waiting until the DOM
is fully loaded. Use $( document ).ready()
to achieve loading your script AFTER the DOM
has loaded.
Two: It's best practice to put your code AFTER the actual DOM
elements, not before it. That way the DOM
is "almost" guaranteed to load before your script runs.
IE:
<div class="modal fade" id="overlay">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>Context here</p>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#overlay').modal('show');
setTimeout(function() {
$('#overlay').modal('hide');
}, 5000);
});
</script>
EDIT
I would use .show()
and .hide()
<script>
$(document).ready(function() {
$('#overlay').show();
setTimeout(function() {
$('#overlay').hide();
}, 5000);
});
</script>
Upvotes: 1
Reputation: 625
You have to wrap your call in document ready, to assure it will be called once the page fully loads, like so:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$('#overlay').modal('show');
setTimeout(function() {
$('#overlay').modal('hide');
}, 5000);
});
</script>
<body>
<div class="modal fade" id="overlay">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>Context here</p>
</div>
</div>
</div>
</div>
</body>
Upvotes: 1