Skip to main content

Lavalamp effect

Sliding the background in a navigation to the current element is named lavalamp effect. I found a good tutorial and altered it a bit ...

html:

<div id="teaserNav">

<div id="magTeaser" class="teaserNav active">

<Icon name="BookOpen" />

<span>Magazin</span>

</div>

<div id="magAudio" class="teaserNav">

<Icon name="Headphones" />

<span>Audiotrainer</span>

</div>

<div id="magUbung" class="teaserNav">

<Icon name="Pencil" />

<span>Übungsheft</span>

</div>

</div>

css / sass:

#teaserNav {

display: inline-flex;

flex-direction: row;

flex-wrap: nowrap;

justify-content: center;

align-items: center;

height: 47px;

background-image: url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjQwIiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHJlY3QgeD0iMCIgeT0iMCIgcng9IjQiIHJ5PSI0IiB3aWR0aD0iMTAwIiBoZWlnaHQ9IjQwIiBmaWxsPSIjQ0NEOUUxIiAvPjwvc3ZnPg==');

width: fit-content;

background-repeat: no-repeat;

background-position-x: 2px;

background-position-y: 1px;

transition: all 0.25s ease;

margin: 0 auto;

gap: 1px;

border: 2px solid $lightContrast;

border-radius: 4px;

padding: 1px;

@include for-size(p) {

margin-bottom: 2em;

height: 57px;

background-image: url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTkwIiBoZWlnaHQ9IjUwIiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHJlY3QgeD0iMCIgeT0iMCIgcng9IjQiIHJ5PSI0IiB3aWR0aD0iMTkwIiBoZWlnaHQ9IjUwIiBmaWxsPSIjQ0NEOUUxIiAvPjwvc3ZnPg==');

}

@include for-size(d) {

margin-top: 2em;

}

div {

display: flex;

flex-direction: row;

flex-wrap: nowrap;

justify-content: center;

align-items: center;

gap: 5px;

padding: 0;

font-family: $fontAlternative;

width: 100px;

cursor: pointer;

@include for-size(p) {

padding: 0.5em 1.5em;

width: 190px;

}

svg {

display: none;

@include for-size(p) {

display: inline-block;

}

}

}

}

Javascript:

<script>

const enableBtns = document.querySelectorAll('.teaserNav');

const existingTeasers = document.querySelectorAll('.teaserText');

const teaserNav = document.getElementById('teaserNav');

for (let i = 0; i < enableBtns.length; i++) {

let enableBtn = enableBtns[i];

enableBtn.addEventListener('click', function(e) {

e.preventDefault();

for (let a = 0; a < enableBtns.length; a++) {

let currentBtn = enableBtns[a];

currentBtn.classList.remove('active');

}

enableBtn.classList.add('active');

let posInfos = enableBtn.getBoundingClientRect();

let elemWidth = posInfos.width;

teaserNav.style.backgroundPositionX = i*elemWidth+3 + 'px';

}, false);

}

</script>