Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React: how to make a function work with a variable "getElementById"?

This is my first question here so I will try to explain what I’m trying to do the best I can.

Basicly I have a function the changes the style of an image, but I have 2 images and i didnt want to create 2 different functions for it, i wanted to recive a ID as a variable.

Images:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<a href="https://discord.gg/N8SDJGSzeS" target="_blank"><img className="img imgDiscord" id="discord" src={discord} onMouseEnter={mouseOver} /></a>
<a href="https://docs.google.com/document/d/15nLun4hYEI3l4Zf9MVMZkigGe9FD4Was5dDZLD3E6E8" target="_blank"><img className="img" src={rulesIcon} id="rules" onMouseOver={mouseOver}/></a>

Functions that are working:

function mouseOver(){
  document.getElementById("discord").style.height = "100px";
}

function mouseOver(){
  document.getElementById("rules").style.height = "100px";
}

Basicly i need to pass a string into the function to be able use only one function that work on both images.

For some reason doesnt work, it doesnt give any error but doesnt change the images height as well… and i have no idea why…

Thanks all for reading i really appreciate some help 😛

But like i said i dont want to functions i wanted only one and i tried to do this =>

<a href="https://discord.gg/N8SDJGSzeS" target="_blank"><img className="img imgDiscord" id="discord" src={discord} onMouseEnter={mouseOver("discord")} /></a>
<a href="https://docs.google.com/document/d/15nLun4hYEI3l4Zf9MVMZkigGe9FD4Was5dDZLD3E6E8" target="_blank"><img className="img" src={rulesIcon} id="rules" onMouseOver={mouseOver("rules")}/></a>
function mouseOver(ids){
  document.getElementById(ids).style.height = "100px";
}

>Solution :

One way to do it (code goes inside the relevant component):

const handleMouseOver = height => event =< {
    event.currentTarget.style.height = height;
}

...

<a href="https://discord.gg/N8SDJGSzeS" target="_blank"><img className="img imgDiscord" id="discord" src={discord} onMouseEnter={handleMouseOver("100px"} /></a>

<a href="https://docs.google.com/document/d/15nLun4hYEI3l4Zf9MVMZkigGe9FD4Was5dDZLD3E6E8" target="_blank"><img className="img" src={rulesIcon} id="rules" onMouseOver={handleMouseOver("10px"}}/></a>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading