Front-end Developer Front-end Developer - 2 months ago 8
Javascript Question

mousover mouseout this class visible hidden pure javascript

Each text belongs to a specific image, so when someone is moving the cursor over that image. The text should be shown up and when the cursor goes mouseout the text should be hidden. No jQuerty required please, must be in pure JavaScript. Anyone an idea how I should fix that.



function show() {
document.getElementsByClassName("text").style.visibility = "visible";
}

function hide() {
document.getElementsByClassName("text").style.visibility = "hidden";
}

<div class="row">
<div class="col-md-6 col-sm-12">
<div class="tumb-wrapper">
<a href="www.bbc.com" target="_blank" class="image" onmouseover="show()" onmouseout="hide()">
<img src="img/a-print-screen.png" class="project" alt="a-print-screen"/>
<div class="text">A-picture</div>
</a>
</div>
</div>
<div class="col-md-6 col-sm-12">
<div class="tumb-wrapper">
<a href="www.cnn.com" target="_blank" class="image" onmouseover="show()" onmouseout="hide()">
<img src="img/x-picture.png" class="project" alt="x-print-screen"/>
<div class="text">x-picture</div>
</a>
</div>
</div>
</div>




Answer

The command document.getElementsByClassName("text"); returns a List of elements opposed to document.getElementById("text"); which returns just one element. So to use one element to change its style you have to use array notation document.getElementsByClassName("text")[0] for example for the first element.

I used a for loop to iterate over every list element in the code sample below:

function show(myText) {
  var elements = document.getElementsByClassName(myText)
  
  for(var i = 0; i < elements.length; i++){
      elements[i].style.visibility = "visible";
  }
} 

function hide(myText) {
  var elements = document.getElementsByClassName(myText)
  
  for(var i = 0; i < elements.length; i++){
      elements[i].style.visibility = "hidden";
  }
}
<div class="row">
  <div class="col-md-6 col-sm-12">
    <div class="tumb-wrapper">
      <a href="www.bbc.com" target="_blank" class="image" >
        <img src="https://placeholdit.imgix.net/~text?txtsize=28&bg=0099ff&txtclr=ffffff&txt=300%C3%97300&w=300&h=300&fm=png" class="project" alt="a-print-screen" onmouseover="show('text1')" onmouseout="hide('text1')"/>
        <div class="text1">A-picture</div>
      </a>
    </div>
  </div>
  
  <div class="col-md-6 col-sm-12">
    <div class="tumb-wrapper">
      <a href="www.cnn.com" target="_blank" class="image" >
        <img src="https://www.dreamhost.com/blog/wp-content/uploads/2015/10/DHC_blog-image-01-300x300.jpg" class="project" alt="x-print-screen" onmouseover="show('text2')" onmouseout="hide('text2')" />
        <div class="text2">x-picture</div>
      </a>
    </div>
  </div>
</div>