I’m trying to implement a JavaScript function for a HTML page that simply reveals text on mouse down. I want to apply this multiple times so don’t want to have to create a function for each event.
The below code works fine…
function showSkillInfo() {
if (skill1Info.style.display === 'none') {
skill1Info.style.display = 'grid';
} else {
skill1Info.style.display = 'none';
};
};
skill1.onmousedown = showSkillInfo;
But this block of code seems to have no response…
function showSkillInfo2(skill) {
if (skill.style.display === 'none') {
skill.style.display = 'grid'
} else {
skill.style.display = 'none'
};
};
skill1.onmousedown = showSkillInfo2(skill1Info);
Can anyone tell me why the second function isn’t working the same way the first function is?
3
Answers
I think reason why the second function is not working the same way the first function is because you are invoking the function showSkillInfo2 immediately when you assign it to the onmousedown event handler of skill1.To fix this, you can pass the function reference showSkillInfo2 to the onmousedown event handler without invoking it:
I hope this helps you
The
.onmousedown
attribute is a callback function called when a specific event is triggered (mouse down in that case, but all other events work the same way). This means that a reference to a function or a lambda function must be specified for it to work. The first example is indeed a reference to a function and works as expected. The second one, on the other hand, is a call to a function and it is its return value (undefined
) that will be affected toskill1.onmousedown
. For it to work as intended, you need to specify a new function that will be called with the right parameter. The best way to do this is using lambda functions, like this:skill1.onmousedown = () => showSkillInfo2(skill1Info);
This way,
skill1.onmousedown
has the value of a function with no parameter, and it can be called when the associated event is triggered.This line:
skill1.onmousedown = showSkillInfo2(skill1Info);
is being called immediately, beforeskill
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: