Home > Software design >  How to swap <div> elements by using "mouseover" event?
How to swap <div> elements by using "mouseover" event?

Time:03-01

let wrapperSt = document.querySelector(".wrapper");

for(i=0; i<100; i  ){
let divGroup = document.createElement('div');
wrapperSt.append(divGroup);
divGroup.className= 'pixel';
divGroup.textContent= '';
}

I've created the div element called "pixel" by using loop because, i need couple hundreds of them. (I'll use them as a little boxes that could change color)

But, i want these boxes ("pixel" div) to turn brown and sustain (style.backgroundColor ="brown";)

So, i created another div that will replace the previous div ("pixel").

let selectPx = document.getElementsByClassName("pixel");

selectPx.addEventListener("mouseover", function(){

let pxChange = createElement("div");
//This is where i got stuck!

})

I could not finish my code, i found it a bit complicated even if it is probably something very simple.

Any suggestions or piece of information would be very helpful. Thank you.

CodePudding user response:

Not sure exactly what you are trying to do... I think you are trying to change the color of the div that your mouse is over? If so, you have a couple of issues with your code. Instead of adding the event listener to the list of divs, you need to add it to each one individually. Also, you should only need to change the background color of each element instead of creating a new one each time.

let selectPx = document.querySelectorAll(".pixel");

selectPx.forEach(pixel => {
  pixel.addEventListener("mouseover", () => {
    pixel.style.backgroundColor = "brown";
  });
});

CodePudding user response:

I'm not sure why you have to create a new div inside the first one. In your code, when you trigger the mouseover event you can get the div under the mouse and apply the style to it:

let selectPx = document.getElementsByClassName("pixel");

selectPx.addEventListener("mouseover", function(evt){

    let divUnderMouse = evt.target;
    divUnderMouse.style.backgroundColor ="brown";

})

I haven't tried it but it should work

  • Related