event onmouseover : function launched many times when a <div> includes a <div> - javascript

I have a javascript event onmouseover which is linked to a <div> called div1. As soons as the mouse enter the <div>, it writes something into the console. Right.
If i include an other <div> called div2 into the first one, the problem is that the event will be launched at each time the mouse goes from the first into the second, without escaping from div1. The event should be launched only one time, when the mouse enters div1
The code is pretty simple and can be tested here (please open a js console and put your mouse between red and blue)
<html>
<head>
<style>
#div1{
position : absolute ;
top: 100px;
left: 100px;
width : 200px;
height : 200px;
background : red;
}
#div2{
position : absolute ;
top: 10px;
left: 10px;
width : 100px;
height : 100px;
background : blue;
}
</style>
</head>
<body>
<div id="div1" >
<div id="div2">
</div>
</div>
</body>
<script>
var div1 = document.getElementById('div1');
div1.onmouseover = function(){
console.log('Function launched!');
};
</script>
</html>
In my website, it sends an AJAX request at each event... so it involves to many data transfer.

Use next(), previous() methods or use nth-child or nth-of-type. Thanks and Good luck

Try this.
<script>
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
flag = 0;
div1.onmouseover = function(event){
if (event.target === this && flag == 0)
{
console.log('ok');
}
};
div1.onmouseout = function(event){
if (event.target === this)
{
flag = 0;
}
};
div2.onmouseover = function(event){
if (event.target === this)
{
flag = 1;
}
};
</script>
The above code will not allow to listen mouse over event of inner div.

Try to stop the event propagation by using stopPropagation().
function myEventHandler(e)
{
if (!e)
e = window.event;
//IE9 & Other Browsers
if (e.stopPropagation) {
e.stopPropagation();
}
//IE8 and Lower
else {
e.cancelBubble = true;
}
}

Related

Javascript keydown event twice to cancel

My intention is to make div when keydown, and remove div when the same key is pressed again.
This is my code.
let keydown = false;
document.addEventListener('keydown', function(e) {
if (e.code === 'Space') {
if (!keydown) {
keydown = true;
console.log("space")
e.preventDefault(); //space doesn't manipulate position
$("body").append($("<div id='refactor'></div>"))
$(refactor).append($(".highlight").text())
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
What should I do to remove the div when Space is hit again?
First of all...jquery...avoid this bloatware by all means, please...
Of course this is based on what you've asked here, but I'd recommend instead of store true/false for the pressed key, store the new div element instead. This way, you'll have instant access to it without need search in the DOM.
To remove a node from the DOM, you just need execute node.removeChild(child)
let div = null;
document.addEventListener('keydown', function(e) {
if (e.code === 'Space') {
console.log("space")
e.preventDefault(); //space doesn't manipulate position
if (div)
{
//remove div from DOM
div.parentNode.removeChild(div);
div = null;
}
else
{
//create new div
div = document.createElement("div");
div.id = "refactor";
div.textContent = document.querySelector(".highlight").textContent;
document.body.appendChild(div);
}
}
})
#refactor
{
background-color: lightgreen;
}
<div class="highlight">test</div>
If your whole goal is to show/hide an element, than you should do so via CSS instead of adding/removing elements from DOM, it's significantly faster and allows add additional animations/styles:
let div = document.getElementById("refactor");
document.addEventListener('keydown', function(e) {
if (e.code === 'Space') {
console.log("space")
e.preventDefault(); //space doesn't manipulate position
if (div.classList.contains("hidden"))
{
div.textContent = document.querySelector(".highlight").textContent + " " + Date();
}
div.classList.toggle("hidden");
}
})
#refactor
{
background-color: lightgreen;
transition: height 0.5s, width 0.5s, background-color 0.5s;
height: 1.5em;
width: 100%;
overflow: hidden;
}
#refactor.hidden
{
height: 0;
width: 0;
background-color: pink;
}
<div class="highlight">test</div>
<div id="refactor" class="hidden"></div>
<div>blah</div>

How can i simulate browser events using javascript

I want to simuate the zoom In and zoom out events of browser using javascript. Like in MAC you use Command + to zoom and in Windows Control +. I want to show the same effect as these commands, so I thought of triggering these using vanilla javascript. But not able to achieve anything till now. Has anyone implemented it?
To simulate the event, I am creating the event of keydown with Command and = (zoomIn in case of Mac), but it is not triggering the zoom event :-
let e = new Event("keydown", {"bubbles": true, "cancelable": true});
e.key = "="; // just enter the char you want to send
e.keyCode = 187;
e.which = e.keyCode;
e.altKey = false;
e.ctrlKey = false;
e.shiftKey = false;
e.metaKey = true;
this.dispatchEvent(e);
To verify, I am listening for the zoom event, the manual browser zoom, and javascript zoom both are going inside the if statement.
document.addEventListener('keydown',function(e) {
if (e.keyCode == 187 && e.metaKey) {
console.log('this is getting triggered');
//debugger;
return true;
}
});
You can try to emulate that behavior with CSS property transform: scale()
<!DOCTYPE html>
<html>
<head>
<style>
#test {
margin: auto;
border: 1px solid black;
width: 200px;
height: 100px;
background-color: white;
color: black;
}
</style>
<script>
//TODO: Increase scale value by x each time you press button
function zoomIn () {
document.getElementById("test").style.transform = "scale(1.5)";
}
function zoomOut () {
document.getElementById("test").style.transform = "scale(0.5)";
}
</script>
<head>
<div id="test">
<p>Test</p>
<button onclick="zoomIn()">Zoom IN</button>
<button onclick="zoomOut()">Zoom OUT</button>
</div>
<html>

Adding keyboard arrow navigation to custom js

I am using wordpress and my content looks like this
<div class="image-wrap"><a class="ajax-load-next" href="http://linktopage.com/2/"><img src="blah1.jpg" alt=""/></a></div><!--nextpage-->
<div class="image-wrap"><a class="ajax-load-next" href="http://linktopage.com/3/"><img src="blahab.jpg" alt=""/></a></div><!--nextpage-->
<div class="image-wrap"><a class="ajax-load-next" href="http://linktopage.com/4/"><img src="blahco.jpg" alt=""/></a></div><!--nextpage-->
<div class="image-wrap"><a class="ajax-load-next" href="http://linktopage.com/5/"><img src="blahneat.jpg" alt=""/></a></div>
I have a custom javascript that loads the next image when the user clicks on the image. Now I want to add left & right keyboard arrow navigation to this script and I don't know how I can I implement to it since I'm not familiar with javascript.
$('body').on('click', '.image-wrap', function(e) { // listen for 'click' on our '.image-wrap' element
e.preventDefault(); // Prevents default behavior on the a element
$.ajax({
url: $(this).find( 'a' ).attr( 'href' ), // the url we are fetching by ajax
success: function (response) {
newImg = $(response).find('.image-wrap').html(), // get the new href link and image from the response, contained in div.image-wrap
$( 'div.image-wrap' ).html( newImg ); // set the new html for our inner div
}
}).fail(function (data) {
if ( window.console && window.console.log ) {
console.log( data ); // log failure to console
}
});
});
EDIT:
By pressing the right arrow key I want it to click the ajax link that is inside image-wrap div which should load the next image. If pressing the left arrow key it should go back to the previous image. Any idea how to do this?
You can use mousetrap.
function GoToLocation(url)
{
window.location = url;
}
Mousetrap.bind("right", function() {
document.getElementById('next-image').click();
});
<script src="https://craig.global.ssl.fastly.net/js/rainbow-custom.min.js?39e99"></script>
<script src="https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.js?bc893"></script>
<div class="image-wrap"><a id="next-image" class="ajax-load-next" href="http://linktopage.com/2/"><img src="blah1.jpg" alt=""/></a></div><!--nextpage-->
<div class="image-wrap"><a id="next-image" class="ajax-load-next" href="http://linktopage.com/3/"><img src="blahab.jpg" alt=""/></a></div><!--nextpage-->
<div class="image-wrap"><a id="next-image" class="ajax-load-next" href="http://linktopage.com/4/"><img src="blahco.jpg" alt=""/></a></div><!--nextpage-->
<div class="image-wrap"><a id="next-image" class="ajax-load-next" href="http://linktopage.com/5/"><img src="blahneat.jpg" alt=""/></a></div>
if you are use attachment.php or image.php based gallery. you can also use this : Wordpress Attachment Page Navigate with Keyboard
You need to bind a handler to the document keyup event, and test the key code for the event. A handy reference to key codes: https://css-tricks.com/snippets/javascript/javascript-keycodes/
Below is an example. When you run it, click in the output panel to give it focus before testing the keys.
var selectedIndex = 0;
var elements = $('.navigable').toArray();
var maxElements = elements.length;
function nextSelection() {
selectedIndex++;
if(selectedIndex >= maxElements) {
selectedIndex = 0;
}
selectElement();
}
function prevSelection() {
selectedIndex--;
if(selectedIndex < 0) {
selectedIndex = maxElements - 1;
}
selectElement();
}
function selectElement() {
$('.navigable').removeClass('selected');
$(elements[selectedIndex]).addClass('selected');
}
handleKeyUp = function(ev) {
if(ev.keyCode == 37) { // left arrow key
prevSelection();
}
if(ev.keyCode == 39) { // right arrow key
nextSelection();
}
if(ev.keyCode == 27) { // escape key
$(document).off('keyup', handleKeyUp);
}
}
$(document).on('keyup', handleKeyUp);
selectElement();
div {
padding: 30px;
margin: 10px;
border: 1px solid #aaa;
background: #fee;
display: inline-block;
}
div.selected {
background: #faa;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navigable">1</div>
<div class="navigable">2</div>
<div class="navigable">3</div>
<br>
<br>
<p> Click in this panel to give it focus. Use arrow keys to navigate between divs. Press `ESC` to disable `keyup` handler.</p>

javascript execute function pressing 'esc' key

I have 2 javascript functions: one of them shows div 'PhotoFull' another hides. 'PhotoFull' is a container Div.. Just black background for another Div inside of it. When the user clicks on black background, PhotoFull dessapears.. but if affects also the Div which is inside of 'PhotoFull' (PhotoFull dessapears while clicking the div which is inside). So For the Div which is inside I use event.stopPropagation();
Both functions work, but I also need to hide Div hideDiv() when "ESC" key is pressed. hideDiv() is executing Div
function showDiv() {
document.getElementById('PhotoFull').style.display = "inherit";
event.stopPropagation();
}
function hideDiv() {
var target = event.target || event.srcElement;
if (event.currentTarget == target) {
document.getElementById('PhotoFull').style.display = "none";
}
}
window.onload=function() {
document.onkeyup = key_event;
}
function key_event(e) {
if (e.keyCode == 27) hideDiv();
}
And HTML:
<div id="PhotoFull" style="position: absolute; width: 100%; height: 100%; background-color: rgba(0,0,0, 0.75); display:none; z-index: 999;" onclick="hideDiv()">
<div style="width: 960px; border-radius: 3px; background-color: #ffffff; margin-top: 100px;">
<img id="one_full" src="numbers/1.jpg" style="max-width: 940px; margin: 10px;" />
</div>
</div>
Without event.stopPropagation(); Pressing ESC button executes function hideDiv() but with it, nothing happens. Don't know why.
Thanks for attention
When you press Esc key it goes in hideDiv function but the condition goes worng due to below reason.
See Debug trace in picture.
See watchExpression section in debugger. I have added event object to watch.
You can see full object description in watchExpression in above image.
You have write below condition in hideDiv function
var target = event.target || event.srcElement;
if (event.currentTarget == target) {
document.getElementById('PhotoFull').style.display = "none";
}
in debug trace you can see that event.currentTarget is body target local variable in the hideDiv function is document because you have added your listener for document object canbe seen from your code
window.onload=function() {
document.onkeyup = key_event;
}
So the solution is you have to register event listener on proper object which is body.
use below code for window.onload function..
window.onload=function() {
document.body.onkeyup = key_event;
}
window.onkeypress = keypress;
function keypress(event) {
if (event.keyCode == 27) {
alert("Hidding div *magic runing...*");
}
}
You should consider using onkeypress event to handle it.
Try this,
document.onkeydown=function(e){
if(e.which == 27) {
hidediv();
return false;
}
}

click anywhere to close div inside and outside

This is a jscript to close the window when someone clicks anywhere outsite the Div to close.
my question is to make this window close when someone clicks on this by performing the action.
<div id="box"
style="height: 3em; position:absolute; top: 20%; left: 15%; border: 3px double">
<p>Click anywhere outside this box to close it.
</div>
<script>
document.onclick = function (e) {
e = e || event
var target = e.target || e.srcElement
var box = document.getElementById("box")
do {
if (box == target) {
// Click occured inside the box, do nothing.
return
}
target = target.parentNode
} while (target)
// Click was outside the box, hide it.
box.style.display = "none"
}
</script>
How to make a Div close when the click was occurred inside the DIV
In your HTML code itself,
<div id='box' style='height:10px; width:10px' onclick='CloseMe(this)'>...</div>
Implement the CloseMe function
function CloseMe( obj )
{
obj.style.display = 'none';
}
For the specific thing talking here, I didn't test it but I think change that loop to the following code could make it.
do {
if (box != target) {
// Click occured outside the box, do nothing.
return
}
target = target.parentNode
} while (target)
If you use JQuery you can use the event.stopPropagation(); on the click function for you div
$(function(){
$('html').click(function() {
$('#box').hide();
});
$('#box').click(function(event){
event.stopPropagation();
});
});
http://jsfiddle.net/nCqwy/1/

Categories

Resources