Javascript event handler won't change another element's event handler - javascript

I have two divs, div1 and div2. When div2 is clicked, I want to change the "onmouseover" handler for div1. Here is fiddle code (https://jsfiddle.net/au43obnz/2/):
<div id='div1'
onmouseover='this.style.color=`purple`'
onmouseout='this.style.color=`black`'
onclick='this.onmouseover=null; this.onmouseout = null;'>
hello
</div>
<br>
<div id='div2'
onclick="div1 = document.getElementById(`div1`); div1.style.color=`blue`; div1.onmouseover = 'this.style.color=`yellow`';">
world
</div>
div2's onclick handler is working when I try to change another element of div1 (e.g. div1.style.color='blue'), and div1's onclick handler is successfully changing the onmouseover function for itself (e.g. onclick='this.onmouseover=null; this.onmouseout = null;).
But the div2 onclick handler won't change the onmouseover function for div1. I've tried changing div1.onmouseover = "this.style.color='yellow'" to div1.onmouseover = "document.getElementById('div1').style.color='yellow'", but it still doesn't work.
Anyone know what's going on here?

A control variable can be used to drive the program. In this way, the necessary conditions for directing the program are checked. In the solution below, the old mouseover event of the first <div> element is fired unless the second <div> is clicked; After clicking the second <div>, the new mouseover event of the first <div> is fired.
const div1 = document.getElementById('div1');
const div2 = document.getElementById('div2');
let passive = false, newEventHandler = false;
/* old mouse over event */
div1.addEventListener('mouseover', function() {
if(!passive && !newEventHandler) {
this.style.color = "purple";
console.log("old mouse over");
}
});
/* new mouse over event */
div1.addEventListener('mouseover', function() {
if(newEventHandler) {
this.style.color = "yellow";
console.log("new mouse over");
}
});
/* passive mouse out event */
div1.addEventListener('mouseout', function() {
if(!passive)
this.style.color = "black";
});
/* conditions */
div1.addEventListener('click', function() {
passive = true;
});
/* conditions */
div2.addEventListener('click', function() {
div1.style.color = "blue";
newEventHandler = true;
});
<div id='div1'>hello</div><br>
<div id='div2'>world</div>

Related

Why after adding elements to the document the addEventListener stop working?

I have two .addEvenetListener in my code but one of them stop working after adding a div to my
document.addEventListener("mousemove", (e) => { mouseMove(e) }, false);
document.body.addEventListener("click", function(e){
e = e || window.event;
if (e.which == 1) fire();
}, false);
function fire(){
let bullet = `<div class="bullet" style="left:${shooterPlace.x}px;top:${shooterPlace.y}px;"></div>`;
document.getElementById("space").innerHTML += bullet;
}
After clicking, the GUN that I made stops rotating due to the stop of the eventlistener
HTML:
<div class="body-copier" id="space">
<div id="gun">
<div id="gun-shooter-place"></div>
</div>
</div>
Try this
let bullet = document.createElement("div");
Object.assign(bullet,{class:"bullet",style:`left:${shooterPlace.x}px;top:${shooterPlace.y}px;`});
document.getElementById("space").append(bullet);
Your .space element is edited out of DOM, so it loses it's eventListeners as Your innerHtml+="something new" is the same as .innerHtml="something berfore with something new" .
You want to add additional element to DOm but .innerHtml doesn't do this.
Anyway You didn't provide reproducable code (html missing) so i don't know where is Your gun element (i suppose it's inside .space element)

Is it possible to disable autoscrolling when middle mouse button is down in Chrome?

I want to get MouseEvent while I press down middle mouse button on a div and drag the cursor out of the div.
The problem is that when my web page is scrollable, I get scroll icon as soon as I press down middle mouse button, which I don't want.
I know calling preventDefault() keeps the autoscrolling from being called but it also breaks my getting MouseEvent if my web page is in iframe.
I made a simple code snippet you can try and understand the issue.
Steps;
Run code snippet
Move mouse cursor over yellow div
Press down middle mouse button
At this point, you notice scroll is triggered.
Still holding middle button down, move cursor out of the yellow div and iframe
Notice text in yellow div is still updated.
Click anywhere to disable scroll.
Check 'Call preventDefault' checkbox and re-run steps from #2 to #4.
Notice text in yellow div is NOT updated anymore.
As you can see, preventDefault disables the autoscrolling but breaks the MouseEvent.
var captured = false;
const myDiv = document.querySelector("#myDiv");
const releaseMouse = function() {
document.removeEventListener('mousemove', myHandler);
document.removeEventListener('mouseup', myHandler);
myDiv.addEventListener('mousemove', myHandler);
myDiv.addEventListener('mouseup', myHandler);
captured = false;
};
const captureMouse = function() {
myDiv.removeEventListener('mousemove', myHandler);
myDiv.removeEventListener('mouseup', myHandler);
document.addEventListener('mousemove', myHandler);
document.addEventListener('mouseup', myHandler);
captured = true;
};
const myHandler = function(ev) {
const message = `${ev.type} (${ev.clientX},${ev.clientY}) ${ev.currentTarget.tagName || "Document"}`;
switch (ev.type) {
case 'mousedown':
if (ev.buttons == 4) {
captureMouse();
myDiv.innerHTML = message;
if (document.querySelector("#checkbox1").checked) {
ev.preventDefault();
}
}
break;
case 'mousemove':
if (captured) {
myDiv.innerHTML = message;
}
break;
case 'mouseup':
releaseMouse();
myDiv.innerHTML = message;
break;
}
};
myDiv.addEventListener('mousedown', myHandler);
<div style="height: 2000px;">
<div id="myDiv" style="width: 500px; height: 150px; background-color: yellow;"></div>
<input type="checkbox" id="checkbox1" name="checkbox1">
<label for="checkbox1">Call preventDefault</label>
</div>

Attached event listener on mouseover

I'm very new to Javascript and is trying to attach an anonymous function to an event listener. What the function does is that when mouseover the first element, a message will be displayed in the second element depending on the length of the text within the first element.
However, when I hover my mouse over the first element, nothing happens. Because I'm new to JavaScript, I'm not sure what I did wrong.
function checkLength(event, minLength){
var el, elementTwo;
el = event.target;
elementTwo = el.nextSibling;
if(el.value.length < minLength){
elementTwo.innerHTML = "not enough";
} else {
elementTwo.innerHTML = "enough";
}
}
var elUserName = document.getElementById("one");
elUserName.addEventListener("mouseover", function(event){
checkLength(event, 5);
}, false);
<div>
<div id="one">Bob</div>
<div id="two"></div>
</div>
To access the text of the element you use textContent. value is for inputs.
Also, you need to select the next element sibling, not just the next sibling node.
function checkLength(event, minLength){
var el, elementTwo;
el = event.target;
elementTwo = el.nextElementSibling;
if(el.textContent.length < minLength){
elementTwo.innerHTML = "not enough";
} else {
elementTwo.innerHTML = "enough";
}
}
var elUserName = document.getElementById("one");
elUserName.addEventListener("mouseover", function(event){
checkLength(event, 5);
}, false);
<div>
<div id="one">Bob</div>
<div id="two"></div>
</div>

How to manage events on a specific div?

I would like to catch some events for a specific div if the user clicked on the div (focus the div), keyboard events are catch (not if the last click was out of the div (unfocus the div)
I tried some things, but haven't succeeded : JSFiddle
document.getElementById("box").onkeydown = function(event) {
if (event.keyCode == 13) { // ENTER
alert("Key ENTER pressed");
}
}
This code doesn't work even if I click on the div.
Pure JS solution please
The div element isn't interactive content by default. This means that there isn't a case where the return key will ever trigger on it. If you want your div element to be interactive you can give it the contenteditable attribute:
<div id="box" contenteditable></div>
In order to now fire the event you need to first focus the div element (by clicking or tabbing into it). Now any key you press will be handled by your onkeydown event.
JSFiddle demo.
Giving the 'div' a tabindex should do the trick, so the div can have the focus:
<div id="box" tabindex="-1"></div>
If you click on the div it gets the focus and you can catch the event.
JSFIDDEL
If you set 'tabindex' > 0 you can also select the div using TAB.
You could catch all the click events, then check if the event target was inside the div:
var focus_on_div = false;
document.onclick = function(event) {
if(event.target.getAttribute('id') == 'mydiv') {
focus_on_div = true;
} else {
focus_on_div = false;
}
}
document.onkeyup = function(event) {
if (focus_on_div) {
// do stuff
}
}
try this code i hope this work
var mousePosition = {x:0, y:0};
document.addEventListener('mousemove', function(mouseMoveEvent){
mousePosition.x = mouseMoveEvent.pageX;
mousePosition.y = mouseMoveEvent.pageY;
}, false);
window.onkeydown = function(event) {
var x = mousePosition.x;
var y = mousePosition.y;
var elementMouseIsOver = document.elementFromPoint(x, y);
if(elementMouseIsOver.id == "box" && event.keyCode == "13") {
alert("You Hate Enter Dont You?");
}
}
DEMO

How to dismiss a popup bubble with one click over ono-popup region

I am using the following code to create a popup bubble when a user double-clicks on the webpage:
function displaySomething(x, y) {
var div = document.createElement("div");
div.id = "displaySomething_div";
....
}
var listener = function (event) {
if (event.button == 0 ) {
var div = document.getElementById("displaySomething_div");
if (div) {
document.body.removeChild(div);
}
displaySomething(event.pageX, event.pageY);
}
};
document.addEventListener("dblclick", listener, false);
Currently, the popup bubble will only be dismissed when I double-click on the page or on the bubble.
Is it possible to dismiss the popup bubble only when a single-click over non-bubble area of the page is made? That is, if I click or select over the bubble, the bubble will stay there.
Add a click handler to the popup div which stops propagation of the click event, and then you can safely attach a click handler to the document parent.
Example: http://jsfiddle.net/M6asx/
function displaySomething(x, y) {
var div = document.createElement("div");
div.id = "displaySomething_div";
...
div.addEventListener('click', function(e) { e.stopPropagation(); }, false);
}
var listener = function (event) {
if (event.button == 0) {
var div = document.getElementById("displaySomething_div");
if (div) {
document.body.removeChild(div);
} else {
displaySomething(event.pageX, event.pageY);
}
}
};
document.addEventListener('click', listener, false);

Categories

Resources