Home > database >  I am trying to change the text content of multiple buttons upon hover
I am trying to change the text content of multiple buttons upon hover

Time:09-29

I am trying to create a script that will display a different text content when the mouse is hovered over a specific button. I am building a portfolio website, and wish to have the title of the project, and when hovered display a description of the project before clicking.

I am able to change the content of a single button using JS by:

let newText = "New text goes here"

let btn = document.querySelector(".btn");

btn.addEventListener("mouseover", function() {
  this.textContent = newText;
})
btn.addEventListener("mouseout", function() {
    this.textContent = "Existing Text";
  }) 

I will obviously need more than one button to add my projects to the page, so I was looking for ways to simplify this. I am currently trying to run something like:

const btn = document.getElementsByClassName('btn');

const DESCRIPTIONS = {
  "projectOne": "projectOne text goes here",
  "projectTwo": "projectTwo text goes here"
};

btn.addEventListener("mouseover", ({target}) => {
  this.innerText = DESCRIPTIONS[target.id];
  console.log(target);
})

But I'm getting the error: Uncaught TypeError: btn.addEventListener is not a function, although I can console.log(btn) and I can see the current array of buttons that I have created for projects.

I'm not sure if this is the perfect way to go about things, but all help would be greatly appreciated, as I'm scratching my head a little bit on this one.

I'm happy to supply any extra information that I've missed.

Thanks in advance,

Kaimac

CodePudding user response:

You could definitely make it more modular if you have the button selectors and corresponding action encapsulated in an object/array. Think about a map of buttons vs descriptions. Then you can have a common function where you'd be using document.querySelector('.buttonClassName') to find the button and then add necessary callbacks to the click event. This way, your js wouldn't have similar working code all over and would be cleaner.

CodePudding user response:

getElementsByClassName returns an array, so you need to loop over the elements:

const btn = document.getElementsByClassName('btn');

const DESCRIPTIONS = {
  "projectOne": "projectOne text goes here",
  "projectTwo": "projectTwo text goes here"
};

var i = 0,
  length = btn.length;
for (i; i < length; i  ) {
  if (document.addEventListener) {
    btn[i].addEventListener("mouseover", ({
      target
    }) => {
      this.innerText = DESCRIPTIONS[target.id];
      console.log(target);
    })
  } else {
    btn[i].attachEvent("mouseover", ({
      target
    }) => {
      this.innerText = DESCRIPTIONS[target.id];
      console.log(target);
    })
  };
};
btn.addEventListener("mouseover", ({
  target
}) => {
  this.innerText = DESCRIPTIONS[target.id];
  console.log(target);
})

  • Related