As the title states, my onMouseOver event listener is not working. I'm able to create a 'hover' pseudo class in CSS and have it work that way but I want to create an event listener for this to work.
Code:
let container = document.getElementById('container');
//function to create 16x16 grid
function gridSquares () {
for (x = 0; x < 256; x++) {
let squares = document.createElement('div');
squares.className = 'grid-square';
container.appendChild(squares);
//mouse-over event listener for each grid
squares.addEventListener('onmouseover', function () {
const gridSquare = document.getElementsByClassName('grid-square');
gridSquare.setAttribute('style', 'background: yellow');
});
}
}
gridSquares();
I've created a div in my HTML with an ID of 'container' as well.
Any ideas?
Pretty sure is not
squares.addEventListener('onmouseover', function() {...
but is:
squares.addEventListener('mouseover', function() {...
You should remove 'on' inside the event listener
Related
I have been working on an html/css/javascript 'etch-a-sketch' style project.
In a nutshell I have a grid of div elements with a mouseenter event:
const fillInGrid = document.querySelectorAll(".gridSquares");
fillInGrid.forEach((div) => {
div.addEventListener('mouseenter', (e) => {
div.style.backgroundColor = 'black';
});
});
In the project I have a reset button that removes the child elements from the grid and replaces them with new divs, two prompts where a number of rows and columns specified by the user which then generates a new grid:
const resetButton = document.querySelector("#reset");
resetButton.addEventListener('click', (e) => {
const resetEvent = document.getElementById('container');
while (resetEvent.lastElementChild) {
resetEvent.removeChild(resetEvent.lastElementChild);
};
newGrid();
}
);
However, after clicking reset and choosing dimensions for a new grid, the grid is generated but the grid loses responsiveness to the mouseenter event because I'm assuming the event is being removed along with the divs, is there a way to re-add the event or a method alternative that can remove the divs without the associated event?
A link to a codepen demonstrating the issue: https://codepen.io/MaBuCode/pen/eYpjwOV
Instead of adding multiple event listeners on the child elements, you can add a single event listener at the containing element. This way, your code will become more performant and you will also get to catch any event that gets triggered on the dynamically (newly created) elements.
You will need to replace the mouseenter event with the mouseover event, that supports bubbling.
Here's the code to add and replace the mouseenter event:
// // One event listener to rule them all:
document.getElementById("container").addEventListener('mouseover', (e)=>{
if ( e.target.classList.contains('gridSquares')){
e.target.style.backgroundColor = 'black';
}
});
You can now get rid of the individual div event listener:
fillInGrid.forEach((div) => {
div.addEventListener('mouseenter', (e) => {
div.style.backgroundColor = 'black';
});
});
Codepen Demo
Tip: I have also refactored the ’gridCreator' function to reduce the number of appendChild operations, and instead replaced it with a simple string concatenation to make the code more performant:
function gridCreator(gridSize) {
let content = "";
for (let i = 0; i < gridSize; i++) {
content += "<div class='gridSquares'></div>";
}
document.getElementById("container").innerHTML = content;
}
By using the approach above, you can also omit the code that removes the .container child elements in the resetButton code.
I use javaScript code to hide all div width class:article_content and to display only the div with the id which I selected.But I can understand how to change button's color by article,I look for the exemple in W3School but I use a carusel and the exemple from W3S dosen't work.Here the link:https://carsworldro.000webhostapp.com/button.html
this is the function that fired on each click event
function openArticle(evt, articleName) {
var i, cars_content;
cars_content = document.getElementsByClassName("article_content");
for (i = 0; i < cars_content.length; i++) {
cars_content[i].style.display = "none";
}
document.getElementById(articleName).style.display = "block";
}
to change the button color in your example link you need to add to the function "openArticle"
evt.target.style.background = 'red'
the evt argument in your code or event parameter in general is giving you access to the dom of the HTML element that fired the event
your code need to be like that
function openArticle(evt, articleName) {
var i, cars_content;
cars_content = document.getElementsByClassName("article_content");
for (i = 0; i < cars_content.length; i++) {
cars_content[i].style.display = "none";
}
document.getElementById(articleName).style.display = "block";
console.log(evt.target) ;
evt.target.style.background = 'red'
}
I made an EventListener for a few <div> elements, now i want do change the opacity on a child of this specific element to change if the EventListener is true on this specific element. How do I write that with jQuery or Javascript? I already wrote the pseudoquote, which I think should work. I have a problem to translate it to js.
var overLay = document.getElementsByClassName("overlay");
for (i = 0; i < overLay.length; i++) {
overLay[i].addEventListener("mouseover", mouseOver);
overLay[i].addEventListener("mouseout", mouseOut);
}
function mouseOver() {
document.getElementById("project_07").style.maxWidth = "20px"; //just for testing works!
/* PSEUDOCODE
if overlay[i] (mouseover === true) {
getChildElement of (this/ overlay[i]) // is an <img> element
and .style.opacity = ".8";
*/
}
function mouseOut() {
document.getElementById("project_07").style.maxWidth = "100%";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
With event listeners, you can use this to reference the current element. Because the handler will only react when during a mouseover event, you don't need to check it because it will always be true.
function mouseOver() {
this.querySelector("img").style.opacity = 0.8;
}
Then, if you want to clear the style change on mouseout, just add the same code to your mouseOut function.
function mouseOut() {
this.querySelector("img").style.opacity = 1;
}
Also, if you are only modifying the style of child elements, you could solve this with just css.
.overlay:hover img {
opacity: .8;
}
When event is fired you can access the event prameters. It goes to function as n attribute.
One of properties of the event is target - element that fireв event.
function mouseOver(e) {
e.target.querySelector('img').style.maxWidth = "20px";
}
Try to console.dir(e.target) and research it.
I will simply suggest:
1.assign class to all divs you want to have child change opacity
let's say myClass
$('.myClass').children().on('mouseenter', function(){
$(this).css('opacity', '0.8');
});
I am aware I can use the click function to attach an event to the DIV element but for some reason it is not working for me. Here is how I am creating the DIV element.
function createColorSwatchDiv(color) {
var colorSwatchDiv = $("<div>");
var image = $("<img>");
image.attr("src",color.imageURL);
var label = $("<label>");
label.text(color.title);
colorSwatchDiv.append(image);
return colorSwatchDiv;
}
Then I try to attach the click event like the following:
// run a loop and build the grid layout
for(index = 0; index < colors.length; index++) {
var colorSwatchDiv = createColorSwatchDiv(colors[index]);
// attach the event
colorSwatchDiv.click(function(){
alert('hello world');
});
colorsSection.append(colorSwatchDiv);
}
// add to the dom
$("#color .imageChartOption").after(colorsSection);
But it does not work and no click event is been attached.
following is the code
var $newdiv1 = $("<div id='object1' onClick=Test()>Hello</div>");
$("body").append($newdiv1);
function Test()
{
alert("Clicked");
}
OR
$newdiv1.on('click',function(){alert("hello");});
since you have created the div in a jQuery wrapper you don't need to wrap it again here $(colorSwatchDiv).click(.... Also, are you sure that the colorSwatchDiv variable is referencing the dom element and not the in memory element? Can you apply a class or anything to the elm in the dom?
I have a range of divs (projects) which have a display:none-ed overlay container inside of them, containing additional info.
If the mouse enters the outer div, that overlay container should receive another class making it visible. On mouse leaving the class should be removed.
I solved it using onmouseover="setactive('DIV ID')", but it made the code look pretty messed up so I tried to switch to Eventlisteners. It won't work though and I can't figure out why.
This is my script so far:
// Init Eventlisteners for each container
window.addEventListener("load", start, false);
function start() {
var project_containers = document.getElementsByClassName('content-project')
for (var i = 0; i < project_containers.length; i++) {
project_containers[i].addEventListener("mouseover", setactive(), false)
project_containers[i].addEventListener("mouseout", setinactive(), false)
}
}
// If mouse is over container, add overlay_active class
function setactive() {
var container = document.getElementById(event.currentTarget);
var overlay_class = container.getElementsByClassName("element-overlay")[0];
if (!(overlay_class.className.match(/(?:^|\s)overlay_active(?!\S)/))) {
overlay_class.className += " overlay_active";
}
}
// If mouse is outside the container again, remove overlay_active class
function setinactive() {
var container = document.getElementById(event.currentTarget);
var overlay_class= container.getElementsByClassName("element-overlay")[0];
if (overlay_class.className.match(/(?:^|\s)overlay_active(?!\S)/)) {
overlay_class.className = overlay_class.className.replace(/(?:^|\s)overlay_active(?!\S)/g, '')
}
}
You don't need the id to set container, your functions could be like this:
function setinactive(e) {
var container = e.currentTarget;
//your code
}
}
And then the call:
project_containers[i].addEventListener("mouseout", setinactive, false);