0

I'm busting my head on this script because I don't understand why it isn't working because it's supposed to be very simple, I just want to show and hide a certain div or change it's properties.

Javascript:

function show(x){
    var y = document.getElementByClassName(x);
    y.style.display= 'block';

}
function hide(x){
    var y = document.getElementByClassName(x);
    y.style.display = 'none';

}

HTML:

<a href='http://dreamspark.e-uvt.ro/dreamspark/'target='_blank'onmouseover='show('divdreamspark')'onmouseleave='hide('divdreamspark')'>

CSS:

.divdreamspark {
    display: none;
}

I don't see what I'm doing wrong.

Gaurav Aggarwal
  • 9,809
  • 6
  • 36
  • 74
Alexandru Ianas
  • 95
  • 1
  • 11

1 Answers1

1

There are multiple issues:

  1. You have messed the single quotes in the markup.
  2. There is a typo with the method .getElementsByClassName missing s in the Element part.

update the markup:

<a href='http://dreamspark.e-uvt.ro/dreamspark/'target='_blank' 
   onmouseover='show("divdreamspark")' 
   onmouseleave='hide("divdreamspark")'>

Update the js:

function show(x){
    var y = document.getElementsByClassName(x)[0]; // <---missing s in Element
    y.style.display= 'block';
}
function hide(x){
    var y = document.getElementsByClassName(x)[0]; // <---missing s in Element
    y.style.display = 'none';
}

If the element is single then suffix [0] at the selector (although class selector returns a collection). If you are dealing with multiple elements then you have to use loop to iterate and hide each one of them.

function show(x) {
  var y = document.getElementsByClassName(x);
  [].forEach.call(y, function(i, el) {
    el.style.display = 'block';
  });

}

function hide(x) {
  var y = document.getElementsByClassName(x);
  [].forEach.call(y, function(i, el) {
    el.style.display = 'none';
  });
}
Jai
  • 74,255
  • 12
  • 74
  • 103