Search code examples
javascriptcsssveltekitdynamically-generated

Mouseover Event on Dynamically Loaded Images in Sveltekit


I am dynamically loading images in Sveltekit. They are inside a div along with an overlay div that I want o show when the images is hovered over. I have tried a few different things, including setting the id of the image container to the id of the images loaded, but the id doesn't seem to be getting set.

This is what I have so far:

<div id="gallery">
  {#each data.products as product}
    <div class="imagewrapper">
      <div id={product.id} class="piece">
        <h3 class="name">{product.name}</h3>
        <p class="description">{product.meta_description}</p>
      </div>
      <img
        src={product.images[0].file.url}
        alt={product.name}
        on:focus={() => {}}
        on:mouseover={() =>
          document
            .querySelector(`#${product.id}`)
            .classList.add(".piece__show")}
      />
    </div>
  {/each}
</div>

I am new to Sveltekit! Any advice would be appreciated.


Solution

  • Code is wrong in two ways:

    • In .classList.add(".piece__show") there is a . in front of the class that should not be there, it's not a selector.
    • You should not be doing that anyway, messing with the DOM is not clean and bypasses the compiler. Here e.g. the compiler will not recognize the class as "being used", so if you add it to scoped style, it will just be removed by the compiler with a warning.

    I see no reason why the id would not be applied, unless there just isn't one in your data source.

    Would recommend extracting the contents of the #each to a separate component so you can have local state for each item. E.g.

    <script>
      export let product;
    
      let show = false;
    </script>
    ...
    <div id={product.id} class="piece" class:piece__show={show}>...
    <img ... on:mouseover={() => show = true}/>
    

    (Alternatively, you could also add such state data directly to your source objects instead, then you do not need a separate component.)