2

first time here...

So I try it my best with my limited knowledge to find a solution by myself but I couldn't so please I need your help on this:

How can I trigger a Hover effect on an non-related element (no parent, no child, no sibling)

This is the code I have:

<div id="projects">
  <section class="menu_projects">       
    <ul>
      <li class="1"><a></a></li>
      <li class="2"><a></a></li>
    </ul>
  </section>
  <section class="preview_projects">        
    <div id="preview"></div> 
  </section>
</div>

What I want is when I hover on "Class 1" the "#preview" change the background image and when I hover on "Class 2" the "#preview" change to another background image.

Any suggestion is welcome (CSS, Javascript, other). Thanks all!

1 Answers1

2

So... Here is a solution for javascript.

I entered the images into an array, giving the variable name images. Next, using the forEach() method, I will determine the current li tag. And on event mousemove, I determine the index and pull up the corresponding image from the array.

And additionally... your class names li tags 1 and 2 are not valid for css. I have corrected to li_1 and li_2.

window.onload = function() {
let ul_li = document.querySelectorAll('ul li');
let preview = document.querySelector('#preview');
let images = ['https://s1.1zoom.ru/big0/697/Love_Night_Moon_Trees_Silhouette_Two_Dating_576752_1280x853.jpg', 'https://s1.1zoom.ru/big0/629/Love_Night_Moon_Trees_Silhouette_Two_Dating_574587_1280x853.jpg'];

  ul_li.forEach(function(ul_li_current, index) {
    ul_li_current.addEventListener('mousemove', function() {
      preview.style.backgroundImage = "url('"+ images[index] +"')";
    })
  })
}
#preview {
  width: 300px;
  height: 300px;
  background-size: cover;
}
<div id="projects">
  <section class="menu_projects">       
    <ul>
      <li class="li_1"><a>image 1</a></li>
      <li class="li_2"><a>image 2</a></li>
    </ul>
  </section>
  <section class="preview_projects">        
    <div id="preview"></div> 
  </section>
</div>
s.kuznetsov
  • 14,870
  • 3
  • 10
  • 25