This line: skill1.onmousedown = showSkillInfo2(skill1Info);
is being called immediately, before skill
can be defined, so it doesn't work.
What you'll need to do is put that line within another function and that other function will be assigned as the mousedown
callback function.
Also, you don't need two classes here. You can just have a default class that is in effect all the time, and then change it to the new class upon mousedown
.
Lastly, you shouldn't use HTML event attributes to set up events as this is a nearly 30 year old technique from before we had standards. Instead, separate your HTML and JavaScript.
See the comments inline below:
function showSkillInfo(event) {
// First, determine if the event occured on an element you care to handle
if(event.target.classList.contains("skill")){
// Just use the .toggle() method to toggle the use of a class.
// No if statement needed.
// event.target references the actual element that triggered the event
event.target.classList.toggle("grid");
}
};
// We'll just set up mousedown and mouseup events on a parent element
// of the possible elements that may need to be handled.
// by wrapping your callback inside of another function, you get the
// ability to set up the callback without invoking the "real" code
// that should wait for the event to happen. You can also pass the
// automatically provided reference to the event that triggered the
// callback to the function.
document.querySelector("div").addEventListener("mousedown", function(event) {
showSkillInfo(event);
});
document.querySelector("div").addEventListener("mouseup", function(event) {
showSkillInfo(event);
});
.skill {
color:aqua;
cursor:pointer;
}
.grid {
/* This is sample CSS. Replace with yours. */
color:red;
}
<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer <span class="skill">took a galley</span> of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised <span class="skill">in the 1960s</span> with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker <span class="skill">including versions</span> of Lorem Ipsum.
</div>