I'm building an app in Svelte and I'm trying to add to it a previously written .js file. I tried to import it in the main.js file, but gives me an error: Cannot read properties of null (reading 'offsetHeight') This is the .js file:
[...]
function colorSubheadings() {
// Replace subheading background colors
var redStart = 255;
var greenStart = 255;
var blueStart = 255;
var redEnd = 249;
var greenEnd = 250;
var blueEnd = 251;
var redDiff = redEnd - redStart;
var greenDiff = greenEnd - greenStart;
var blueDiff = blueEnd - blueStart;
var page = document.querySelector('.page');
var pageHeight = page.offsetHeight;
var subheadings = document.getElementsByClassName('.chapter');
for (var i = 0; i < subheadings.length; i++) {
// Get the position relative to .page
var span = subheadings[i].querySelector('span');
var factor = span.offsetTop / pageHeight;
var r = Math.floor(redDiff * factor + redStart);
var g = Math.floor(greenDiff * factor + greenStart);
var b = Math.floor(blueDiff * factor + blueStart);
var color = 'rgb(' + r + ',' + g + ',' + b + ')';
// Color background based on position
span.style.backgroundColor = color;
span.style.boxShadow = '11px 0 0 ' + color + ', -13px 0 0 ' + color;
}
}
[...]
And this is the .svelte file:
<script>
//some functions
</script>
<div class="page">
[...]
<div class="chapter-sidebar">
<div class="sidebar js-sidebar">
<div class="sidebar__wrapper">
<ul class="sidebar__list">
{#each files as { file } (file.name)}
<li class="sidebar__list-item">
<a class="sidebar__link" href="#temp">{file.name.split('.').slice(0, -1).join('.')}</a>
</li>
{/each}
</ul>
</div>
</div>
In the .svelte file there is a lateral navbar, just like this. In vanilla html it works perfectly, but with svelte there are some bugs, like the navBar doesn't "stick" in a place: if I scroll down it remains at the top of the page, insted of remain in a particuar position of the screen, "following" the user's scroll. So, what can i do to use this .js file in my svelte project? I also tried this solution, but it didn't worked for me.
Thanks in advace.
Where is the colorSubheadings() function called?
(I see var subheadings = document.getElementsByClassName('.chapter') but no elements with class 'chapter' in the Svelte file)
I suggest you either try
index.html in yourproject/puplic folder after the <script src="/build/bundle.js"></script> (in case the function is called inside the same .js file).svelte component (.js file inside yourproject/src folder with exported function export colorSubheadings() {...}) import {onMount} from 'svelte'
import {colorSubheadings} from './xy.js'
onMount(()=> {
colorSubheadings()
})
You need to export the function in your js file before you can import it in your .svelte file (or other JS file).
export function colorSubheadings() {
...
}