HomTom Posted April 13, 2020 Share Posted April 13, 2020 The following JS is adding an eventlistener to all 3 **li** elements. HTML <div class="burgerIcon"> <div class="burgerLine"></div> <div class="burgerLine"></div> <div class="burgerLine"></div> </div> JS const burgerLines = document.querySelectorAll('.burgerLine') burgerLines.forEach((burgerLine) => { burgerLine.addEventListener('mouseover', (e) => { console.log('The burger is hovered') TweenMax.to(burgerLine, 0.2, { x: -10 }) }) }) But how can I add the eventlistener only to the first and last **li** elements ? See the Pen ExVjeQZ by itsthomas (@itsthomas) on CodePen Link to comment Share on other sites More sharing options...
ZachSaucier Posted April 13, 2020 Share Posted April 13, 2020 Hey Thomas and welcome to the GreenSock forums! There are several ways to do this. The first is to just change your selector to just select the first and last elements: const burgerLines = document.querySelectorAll('.burgerLine:first-child, .burgerLine:last-child'); Another way is to pass in the index to your forEach and use an if statement to check if it's the first or last: burgerLines.forEach((burgerLine, i) => { if(i === 0 || i === burgerLines.length - 1) { // ... Or you could just set it manually on the first and last (no looping). If you do this, you should make a named function and pass in the name: burgerLines[0].addEventListener('mouseover', myFunc); burgerLines[burgerLines.length - 1].addEventListener('mouseover', myFunc); Each of the above are generic to work with any number of elements. Side note: You can rewrite your tween as so in GSAP 3: gsap.to(burgerLine, {duration: 0.2, x: -10}); Happy tweening! 3 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now