Home > Software design >  Using two querySelector in js
Using two querySelector in js

Time:12-20

I'm trying to use js in a way that when you hover the mouse over text links, the background image changes with each link. I've been able to initiate the Event Listener to the link texts but am unable to direct the output to the background image div (style elemet)

Here is my html code

<div id="livestream">  
      </div>
      <div id="wedding">  
      </div>
      <div id="documentary">  
      </div>

      <div >
          <a href="#">Livestreaming</a> 
          <a href="#">Weddings</a>
          <a href="#">Documentaries</a>
      </div>

My css, which im stuck too;

.landing #documentary{
    background-image: url("/img/pic-01.jpg");
    background-size: cover;
    height: 100vh;
    z-index: -1;
}

.landing #livestream, #wedding, #documentary{
    display: none;
}

.text-box a:nth-child(1):hover{
    color: #e08416;
    transition: 0.4s ease;}
}

And here is my js code

document.querySelector('.text-box a:nth-child(1)').addEventListener('mouseenter', entering);
document.querySelector('.text-box a:nth-child(1)').addEventListener('mouseleave', leaving);

function entering(ev){
    ev.currentTarget.style.display = "block";
    console.log('mouseenter  a');
}

function leaving(ev){
    ev.currentTarget.style.display = "none";
    console.log('mouseleave a');
}

I got stuck here

CodePudding user response:

You could use a querySelector in the entering or leaving method to capture the element you need. Or in this case, it's simpler to call the parentElement of the item.

function entering(ev){
    ev.currentTarget.parentElement.style.display = "block";
    console.log('mouseenter  a');
}

function leaving(ev){
    ev.currentTarget.parentElement.style.display = "none";
    console.log('mouseleave a');
}

CodePudding user response:

Thanks, I applied it and here is how I did it

<!-- Main background | should remain -->
      <video  id="background-video" autoplay loop muted poster="/img/banner.jpg">
        <source src="http://127.0.0.1:5500/media/background.mp4" type="video/mp4">
      </video>

<!-- backgrounds images that will change -->
      <div >
        <img  id="linkImage">  
      </div>

<!-- Links supposed to activate the bg images when hovered  -->
      <div >
          <a href="#" onm ouseenter="changeImg('/img/banner.jpg')" onm ouseleave="hide()">Livestreaming</a> 
          <a href="#" onm ouseenter="changeImg('/img/weddings.jpg')" onm ouseleave="hide()" >Weddings</a>
          <a href="#" onm ouseenter="changeImg('/img/documentary.jpg')" onm ouseleave="hide()" >Documentaries</a>
      </div>
//Changes and unhide background images
function changeImg(imgCharger){    
    document.getElementById('linkImage').src = imgCharger;    
    document.querySelector('.links').style.display = 'block';
}


//Hides background images
function hide(){
    document.querySelector('.links').style.display = 'none';
}
  • Related