skip to Main Content

I’m working on a little thing where i need to check if the img.src is already set or not, in order to prevent it to set continuously, as it does right now. The problem lies in my onMove. How can i do that?

HTML:

<div data-tail></div>

<button type="button" data-src="./dist/img/1.jpg">
  text 1
</button>
<button type="button" data-src="./dist/img/2.jpg">
  text 2
</button>
<button type="button" data-src="./dist/img/3.jpg">
  text 3
</button>

JS:

const tail = document.querySelector('[data-tail]') 

window.addEventListener('mouseenter', onEnter)
window.addEventListener('mousemove', onMove)

onEnter(e) {
  let img = new Image()
  tail.appendChild(img)

  gsap.to(tail, {
    autoAlpha: 1,
    duration: 0.25
  })
}

onMove(e) {
  const el = e.target

  if (el.type == 'button') {
    const img = tail.querySelector('img')
    img.src = el.dataset.src
  }

  gsap.to(tail,{
    x:e.clientX,
    y:e.clientY
  })
}

2

Answers


  1. Yoy may check if the src attribute is already set or not, for example:

    if (el.type == 'button') {
        const img = tail.querySelector('img');
        img.src = img.src || el.dataset.src;
    }
    
    Login or Signup to reply.
  2. You can use the mouseover event, which bubbles:

    const tail = document.querySelector('[data-tail]') 
    
    window.addEventListener('mouseenter', onEnter)
    window.addEventListener('mouseover', onOver)
    window.addEventListener('mousemove', onMove)
    
    function onEnter(e) {
      let img = new Image()
      tail.appendChild(img)
    
      gsap.to(tail, {
        autoAlpha: 1,
        duration: 0.25,
      })
    }
    
    function onOver(e) {
      const el = e.target
    
      if (el.type == 'button') {
        const img = tail.querySelector('img')
        img.src = el.dataset.src
      }
    }
    
    function onMove(e) {
      gsap.to(tail, {
        x: e.clientX,
        y: e.clientY,
      })
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search