0

I'm importing images:

import vanilla from 'url:../../img/flavors/vanilla.jpg';
import chocolate from 'url:../../img/flavors/chocolate.jpg';

I have several p tags that list several flavors:

<p class="cake-flav cake-flav--classic">vanilla</p>
    <p class="cake-flav cake-flav--classic">funfetti</p>
    <p class="cake-flav cake-flav--classic">chocolate</p>

I added a mouseover eventlistener to the container that houses the p tags above:

const flavorsBox = document.createElement('div');
flavorsBox.classList.add('main-content__container--flavors__flavors-box');
flavorsBox.addEventListener('mouseover', function(e){
    const hovered= e.target.closest('.cake-flav');
    if(hovered === null) return;
    flavorImg.style.backgroundImage= '';
    flavorImg.style.backgroundImage= `url(${hovered.textContent})`;
    console.log(flavorImg.style.backgroundImage);
});

I'm currently taking the text content of the p tag that's being hovered and setting the background Image url to the text content in the hopes that it would refer to the named import of the images. What it is doing instead is `url("vanilla") and not referring to vanilla, the named import.

Andrew Stegmaier
  • 3,429
  • 2
  • 14
  • 26
  • 1
    question: why? Why not just write normal CSS that ties those images to specific classes, and then have your JS toggle the class you need by using the `.classList` proper that you already know how to use? You shouldn't need to touch the `.style` attribute except in very rare cases (even for things like JS based animations, you declare a CSS variable on the CSS side and then you update that variable through JS, you don't mess with `.style`) – Mike 'Pomax' Kamermans Jul 27 '21 at 22:37
  • I was hoping for a more dynamic solution where when I hover it automatically changes the background image to the respective image. If I'm understanding your suggestion correctly I'd have to create 13 different classes. – user6279105 Jul 27 '21 at 22:41
  • "you" wouldn't, you would write code that does generates that for you. That's what build systems are for =) – Mike 'Pomax' Kamermans Jul 27 '21 at 22:43

0 Answers0