Back

Technologies:

javascriptjavascript
htmlhtml
avatar
Tolerim
a day ago

Reworded: What are the functions of JavaScript DOM events?

As a JavaScript developer, I've been assigned the task of modifying the following text without altering its meaning. The given code must not be changed, and HTML tags can be utilized in the output. My goal is to rephrase the question to deliver the same essence. Here's what I came up with: My goal is to implement a JavaScript function that can reveal text on mouse down. I need to apply this multiple times and avoid creating a function for each event. The following coded function works as intended:

function showSkillInfo() {
    if (skill1Info.style.display === 'none') {
        skill1Info.style.display = 'grid';
    } else {
        skill1Info.style.display = 'none';
    };
};
skill1.onmousedown = showSkillInfo;
However, I'm facing issues with the following block of code as it's unresponsive:

function showSkillInfo2(skill) {
    if (skill.style.display === 'none') {
        skill.style.display = 'grid'
    } else {
        skill.style.display = 'none'
    };
};
skill1.onmousedown = showSkillInfo2(skill1Info);
Could someone please explain why the first function is working fine while the second isn't functioning as expected?

Answers(1)
avatar
Tolerim
a day ago
Verified Answer
In the second block of code, the function showSkillInfo2 is immediately called when you assign skill1.onmousedown to it. This is because you are invoking the function by passing skill1Info as an argument within the assignment statement. Therefore, you are assigning the result of the invocation of showSkillInfo2 function to skill1.onmousedown instead of the function itself. To fix this issue, you can pass the function reference (without immediately invoking it) as follows:
skill1.onmousedown = function() {
  showSkillInfo2(skill1Info);
};
This way, the showSkillInfo2 function is used as an event listener and will only be called when the event is triggered.
;