I'm a beginner learning to work with vanilla javascript. I have been searching for 2 days, and posting questions in a couple of javascript facebook groups since last night, and I haven't found a solution yet. Maybe I'm not asking the question correctly in my search, but I'm just stuck. If, for some reason, I am bringing up a question that has been answered, I apologize. In my defense, being a beginner sometimes means we are not sure exactly how to search for the answers. Moving on...
I am trying to figure out how to use 2 eventListeners for the same button to change a css property value. I want function1 to run on mousedown and function2 to run on mouseup. I think my problem is occurring with the (event) parameter. Is there a way to make sure the event parameter in function1 is targeting only the event for mousedown? Then point the event in function2 to use the event for mouseup?
This is what I have so far...
html
<button class="my-btn">My button</button>
<div class="my-class">
some content
</div>
Javascript
let myBtn = document.querySelector('.my-btn');
let myClass = document.querySelector('.my-class');
myBtn.addEventListener('mousedown', function1);
myBtn.addEventListener('mouseup', function2);
function function1(event){
myClass.style.bottom = "-16em";
}
function function2(event){
myClass.style.bottom = "0";
}
Good that you have started to work on Js.
I have created a playground which changes the background color on mouseup and mousedown event. Please visit the below link for the same.
https://jsfiddle.net/kqydbwhL/
Also, I feel like in your code.
myBtnshould be replaced withmyClassbecause you are storing the element intomyClassbut while listening to the events you are targetingmyBtnwhich isundefined.Thanks.
I think you updated your code snippet in the problem description. Here is the new playground url having those changes.
https://jsfiddle.net/6pzhjvfL/17/