Laravel - Botstrap Javascript Conflict with Chartjs
Has anyone experienced this?
Bootstrap Javascript
(for modals
, accordion
and other animations) has a conflict for mine Chart.js
.
Here's a cdn link , I used a minified version. (Chart.min.js)
If it helps, I'll show mine script
for the diagram:
<script src="{{ asset('js/Chart.min.js') }}"></script>
<script>
let myChart = document.getElementById('myChart').getContext('2d');
let massPopChart = new Chart(myChart, {
responsive: true,
type:'line',
data:{
labels:['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
datasets:[{
label:'Sales',
data:[
500,
304,
601,
670,
912,
612,
500
],
backgroundColor: 'rgba(129, 207, 238, 1)',
borderWidth: 1,
borderColor: '#000',
hoverBorderWidth: 3,
hoverBorderColor: '#000'
}]
},
options:{
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
},
title:{
display: true,
text: 'Weekly Sales',
fontSize: 25
},
legend:{
position:'bottom',
display:false,
},
layout:{
padding: 50,
}
}
});
</script>
This is a line chart
, which is the default (for testing). The diagram disappears after a second, and because of this. I knew it was because of Bootstrap Javascript
.
Whenever I log out, or comment
out of a tag script
for Bootstrap Javascript
, the chart shows without issue. But mine modal
and others animations
don't work now.
I somehow want both of them to work because I need them.
source to share
This may be the most frustrating (bug / feature / problem) I've ever encountered and got stuck for a few days, but since my boss doesn't accept a “no” answer and I hate giving up, I finally managed to solve it. The answer thought something about html and javascript that I never knew:
Answer:
In <head></head>
your html file you need to change the way you download using app.js
the boot app.js
:
<script src="{{ asset('js/app.js') }}" defer></script>
to that:
<script src="{{ asset('js/app.js') }}"></script>
Note the missing tag defer
.
Explanation:
You may be wondering what does the defer
tag do? And to answer that I give you this little snippet:
<html>
<body>
<script src="https://www.w3schools.com/tags/demo_defer.js" defer></script>
<p id="p1">
Hello World!
</p>
</body>
</html>
It just stops the browser from loading / running the script until the site has been fully parsed. In the above example, the script we are calling contains the following code:
alert(document.getElementById("p1").firstChild.nodeValue);
Basically, your browser is sending an alert with the content of everything inside the p tags. Without the tag, the defer
script will fail because it will run before the p tags have been parsed by the browser, and javascript can only work on what the browser has already parsed.
As far as I've found, removing the defer tag doesn't break anything in the bootstrap, so I don't know why it even has a defer tag.
I'm also not entirely sure why this would be a problem for chart.js. If anyone knows I would love to hear it.
source to share