Hi there,
I’m working on the last responsive design certificate project. I would like to create a certain functionality via vanilla JS.
What I would like to achieve is this: if you hover over “element 1” then “picture A” will show up at X position, you hover over “element 2” and “picture B” will show up at the same X position. On a sidenote, I know this is possible via CSS, however it would require me to reorganise my containers and I wanted to use some JS anyway to practice.
I have found a solution to this:
anchorTribute.addEventListener('mouseover', () => {
previewTribute.classList.toggle('preview-animation');
});
anchorTribute.addEventListener('mouseout', () => {
previewTribute.classList.toggle('preview-animation');
});
This piece of code works perfectly for me, however I would need to apply to each and every one of them almost the same exact code. What I’ve deduced so far in the JS course is that whenever you start to repeat or use an almost identical piece of code, there’s a possibility that you can do it “simpler” or at least arrive at a more complex solution with less code.
For example here’s this code:
anchorArr.forEach((element) => {
element.addEventListener('mouseover', () => {
previewArr.forEach((styling) => {
styling.classList.toggle('preview-animation');
})
});
element.addEventListener('mouseout', () => {
previewArr.forEach((styling) => {
styling.classList.toggle('preview-animation');
})
});
});
While this code applies the intended functionality to the elements, it also triggers all the other elements (in my case “picture A, B, etc…”). I understand why this happens, so I tried to play around with the arrays, since it is structured in a way that anchorArr[0] is what needs to trigger previewArr[0].
I’ve tried a simple for loop, but it’s the same result. I’ve tried somehow pass the current index of anchorArr by using anchorArr.indexOf(element). I’ve tried with a console.log(), I can actually access it, however console says:
anchorArr.indexOf(…).classList is undefined
Then, I tried to create an empty array inside the function, pushing the current index number, then shifting on mouseout.
Uncaught TypeError: testArr.classList is undefined
I guess I just don’t have the necessary experience with JavaScript, but I’m at a point where I consider myself kind of obsessed with this problem.