Topic: MDB 5: Uncaught Reference Error: mdb is not defined
wordfishgroup priority asked 3 years ago
Testing an MDB5 Pro WordPress theme and have run into problems executing javascript as shown on MDB 5 Pro site (https://mdbootstrap.com/docs/standard/data/charts/#section-bar-chart)
Expected behavior
scripts referencing mdb.min.js to execute as per examples. In this ticket I am showing the bar chart example. I expected the output using the Javascript initialization example to show. NOTE: The CSS only example works fine:
<canvas
data-mdb-chart="bar"
data-mdb-dataset-label="Traffic"
data-mdb-labels="['Monday', 'Tuesday' , 'Wednesday' , 'Thursday' , 'Friday' , 'Saturday' , 'Sunday ']"
data-mdb-dataset-data="[2112, 2343, 2545, 3423, 2365, 1985, 987]"
></canvas>
Actual behavior
Uncaught Reference Error: mdb is not defined
Resources (screenshots, code snippets etc.)
Console
(index):44 Uncaught Reference Error: mdb is not defined at (index):44
view-source (line 44)
new mdb.Chart(document.getElementById('bar-chart'), dataBar);
view-source (body excerpt)
<section>
<div class="container-fluid">
<div class="row">
<div class="col-xl-12">
<div class="lc-block">
<script>
// Chart
const dataBar = {
type: 'bar',
data: {
labels: ['Monday', 'Tuesday' , 'Wednesday' , 'Thursday' , 'Friday' , 'Saturday' , 'Sunday '],
datasets: [
{
label: 'Traffic',
data: [2112, 2343, 2545, 3423, 2365, 1985, 987],
},
],
},
};
new mdb.Chart(document.getElementById('bar-chart'), dataBar);
</script>
<canvas id="bar-chart"></canvas>
</div><!-- /lc-block -->
</div><!-- /col -->
</div>
</div>
view-source (footer excerpt)
</footer>
<script src='http://wordfishgroup.local/wp-content/themes/picostrap-mdb5pro/js/popper.min.js?ver=2.5.4' id='Popper-js'></script>
<script src='http://wordfishgroup.local/wp-content/themes/picostrap-mdb5pro/js/mdb.min.js?ver=5.0.0' id='mdb-js'></script>
Grzegorz Bujański staff answered 3 years ago
The code runs from top to bottom, so you need to add HTML first. Otherwise, the JS code will not find the element to operate on.
The same is with importing MDB. But in this situation, the DOMContentLoaded
event will be helpful: https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event
thanks to it, the code will be executed only when the whole page is loaded.
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- ForumUser: Priority
- Premium support: Yes
- Technology: Other
- MDB Version: -
- Device: NA
- Browser: NA
- OS: NA
- Provided sample code: No
- Provided link: Yes
wordfishgroup priority commented 3 years ago
Moving the enqueue of mdb.min.js from footer to header resolved the library not found issue. Inline js called before mdb loaded.
However, the chart was not rendered. To resolve this issue I had to move the HTML above the inline script rather then having it below the script: