how detect mouse click area in document - jquery - javascript - javascript

I have a page with a div element in it. i want when i clicked on outer area of that div element, then fade it out.
but i don't know how detect area of mouse click.
how detect that mouse click point is out of div area or not??

This is not very complicated - you have two options:
1. Asign onclick event to the outer area.
<div id="outer" onclick="$("#inner").fadeOut();">
<div id="inner" onclick="event.cancelBubble=true;/*disable bubling*/">Inner Div</div>
</div>
2. Traverse the dom and compare event.target (event.srcElement)
document.addEventListener("click", function(event) {
var body = document.body;
var target = event.target!=null?event.target:event.srcElement;
var inner = document.getElementById("inner");
while(target!=body) {
if(target==inner) //This means our inner element is clicked - or one of its children
return false;
target=target.parentNode; //Go UP in the document tree
}
$("#inner").fadeOut(); //If we got here, none of element matched our inner DIV, so fade it out
}

One possible jQuery solution:
$(document).on("click", function(e) {
var $div = $("#divId");
if (!$div.is(e.target) && !$div.has(e.target).length) {
$div.fadeOut();
}
});
DEMO: http://jsfiddle.net/5Jb5b/

function clickOn(e)
{
var target = e.target;
var optn = [];
optn.id = target.id;
optn.optnClass = target.className.split(' ');
optn.optnType = target.optnName.toLowerCase();
optn.parent = target.parentNode;
return optn;
}
document.body.onclick = function(e)
{
elem = clickOn(e);
var option_id = elem.id;
alert( 'option ID: '+option_id); // From id or other properties you can compare and find in which area mouse click occured
};

Related

Why is target event referring to parent element when the child element is the element that is being hovered

Upon hovering of a child div, I am attempting to prevent event propagation such that the parent propagation will not be triggered however I am experiencing several issues where the parent onMouseEnter event is being triggered BEFORE the child despite the fact that the element being hovered is the child element.
The event target as identified by (($this)) is also printing the details of the outer <div id="kingOuter"> instead of <div id = "kingMiddle">
Result
Code
$(document).ready(function() {
$(function () {
var outerElement = document.createElement("div");
outerElement.id = "kingOuter";
outerElement.textContent = "King Outer";
var middleElement = document.createElement("div");
middleElement.id = "kingMiddle";
middleElement.textContent = "King Middle";
outerElement.onmouseenter = function(e){
console.log($(this));
console.log("King outer mouse enter");
}
middleElement.onmouseenter = function(e){
console.log("King middle mouse enter");
}
let ppp = document.getElementById('tttest');
outerElement.appendChild(middleElement);
ppp.appendChild(outerElement);
});
})

How to return innertext of sibling element

In GTM i'm trying to return the inner text of a sibling element of the clicked element.
<div class="repair-item-n ">
<div class="repair-slide--54894d33-6c88-488f-95d7-3ec9b6a3ade4">
<div class="restoration_wrap text-center">
<img class="restoration-image">
</div>
<p class="title">Bags</p>
</div>
</div>
For example, on click of class "restoration-image" I want to return the value "Bags".
I have multiple occurrences of this HTML on the page with varinats such as "Shoes", "Hats" etc so I want to know on click of each, which would be the respective text of the "title" class
Try this:
var images = document.querySelectorAll('.restoration-image');
images.forEach(function (image) {
image.addEventListener('click', function (event) {
var parent = this.parentNode;
var nextSibling = parent.nextElementSibling;
alert(nextSibling.innerText)
})
});
This should work for GTM custom JavaScript variables.
function getImgTitle() {
if({{event}} === 'gtm.click') {
var image = {{Click Element}};
var parent = image.parentNode,
nextSibling = parent.nextElementSibling;
return nextSibling.innerText;
}
}
I would do this in a Custom Javascript Variable:
Click - Repair Item Title
function() {
var clickedEl = {{Click Element}};
if (!clickedEl) return;
// Find the mutual parent element
var repairItemEl = clickedEl.closest(".repair-item-n");
if (!repairItemEl) return;
var titleEl = repairItemEl.querySelector(".title");
if (!titleEl) return;
return titleEl.innerText
}}

Create multiple elements and delete a single one JavaScript

I'm working on a JavaScript project where a user can click a button to create a text element. However, I also want a feature where I can click a different button and the element that was created most recently will be removed, so In other words, I want to be able to click a button to create an element and click a different button to undo that action.
The problem I was having was that I created the element, then I would remove the element using:
element.parentNode.removeChild(element); , but it would clear all of the elements that were created under the same variable.
var elem = document.createElement("div");
elem.innerText = "Text";
document.body.appendChild(elem);
This code allows an element to be created with a button click. All elemente that would be created are under the "elem" variable. so when I remove the element "elem", all element are cleared.
Is there a simple way to remove on element at a time that were all created procedurally?
Thanks for any help
When you create the elements, give the a class. When you want to remove an element, just get the last element by the className and remove it.
The below snippet demonstrates it -
for(let i = 0; i<5; i++){
var elem = document.createElement("div");
elem.innerText = "Text " + i;
elem.className = "added";
document.body.appendChild(elem);
}
setTimeout(function(){
var allDivs = document.getElementsByClassName("added");
var lastDiv = allDivs.length-1;
document.body.removeChild(allDivs[lastDiv]);
}, 3000);
I would probably use querySelectors to grab the last element:
// optional
// this is not needed it's just a random string added as
// content so we can see that the last one is removed
function uid() {
return Math.random().toString(36).slice(2);
}
document.querySelector('#add')
.addEventListener('click', (e) => {
const elem = document.createElement('div');
elem.textContent = `Text #${uid()}`;
document.querySelector('#container').appendChild(elem);
// optional - if there are elements to remove,
// enable the undo button
document.querySelector('#undo').removeAttribute('disabled');
});
document.querySelector('#undo')
.addEventListener('click', (e) => {
// grab the last child and remove
document.querySelector('#container > div:last-child').remove();
// optional - if there are no more divs we disable the undo button
if (document.querySelectorAll('#container > div').length === 0) {
document.querySelector('#undo').setAttribute('disabled', '');
}
});
<button id="add">Add</button>
<button id="undo" disabled>Undo</button>
<div id="container"></div>

How to add a function on an element that was made after DOM creation?

I have a function that creates an html element with an unique ID.
And after that I want that when I click this element I could call a new function.
Quick example:
1) I click a button "Create element";
2) An element is created with id of "New_Element";
3) I click the "New_Element";
4) I get a function that was already preset to this element.
My current code for creating an element.
var pageRows = document.getElementsByClassName('pageRows');
var pageRowID = "section";
var el = document.createElement('section');
el.setAttribute('id', pageRowID + pageRows.length);
var row = document.getElementById('allNewRows');
row.parentNode.appendChild(el);
el.innerText = "New " + pageRows.length + " ROW!";
Now that the Element of id "pageRowId0" is created I want to have a function that works when I click this element.
Best wishes.
Thanks for helping.
You can do element.onclick= function(){}
var pageRows = document.getElementsByClassName('pageRows');
var pageRowID = "section";
var el = document.createElement('section');
el.setAttribute('id', pageRowID + pageRows.length);
el.onclick = function(){
/*write your fn here*/
};
var row = document.getElementById('allNewRows');
row.parentNode.appendChild(el);
el.innerText = "New " + pageRows.length + " ROW!";
You can use event delegation:
var row = document.getElementById('allNewRows');
row.parentNode.onclick = function(e) {
if (e.target.nodeName.toLowerCase() == 'select') {
//click on target select element
}
};
The snippet below has two parts. The first piece of code allows you to add a bunch of elements with different texts to the document.
The second parts shows the text of the element you clicked.
You will notice that the click event handler is just assigned to the parent element in which the new elements are added. No explicit click event handlers are bound to the new element.
I like to use addEventListener, because I think it's better to add a listener for a specific goal than to override any other event listeners by bluntly setting 'onclick', but that's a matter of opinion.
// Only run this code when the DOM is loaded, so we can be sure the proper elements exist.
window.addEventListener('DOMContentLoaded', function(){
// The code to add an element when the add button was clicked.
document.getElementById('add').addEventListener('click', function() {
var element = document.createElement('div');
element.innerText = document.getElementById('text').value;
element.className = 'clickableElement';
document.getElementById('elements').appendChild(element);
});
// Click event handler for the 'elements' div and everything in it.
document.getElementById('elements').addEventListener('click', function(event) {
var target = event.target; // The element that was clicked
// Check if the clicked element is indeed the right one.
if (target.classList.contains('clickableElement')) {
alert(target.innerText);
}
});
})
<input id="text" value="test"><button id="add">add</button>
<div id="elements"></div>

Delete a div using "this" with Javascript

What I would like to do is to create a div by clicking on a button. In that div there will be another button if clicked will delete the div that it is in. So potentially the first button will create many div's with this delete button inside but I want the delete button to only delete the div that it is within. Any suggestions?
If you do not need to keep the "delete button" on your page, bind the click event on each of them and use .removeChild on the parent element of the parent div.
FIDDLE DEMO
You can do something like:
<script>
var addDiv = (function() {
var div = document.createElement('div');
div.appendChild(document.createTextNode('some text'));
var button = document.createElement('button');
button.appendChild(document.createTextNode('Remove...'));
button.type = "button";
return function() {
var d = div.cloneNode(true);
var b = button.cloneNode(true);
b.onclick = function() {
var d = this.parentNode;
d.parentNode.removeChild(d);
};
d.appendChild(b);
document.body.appendChild(d);
};
}())
</script>
<button onclick="addDiv()">Add a div</button>
The above is just a trivial example to demonstrate one way to go about it. Note that if you clone an element, listeners added as properties or by addEventListener are dropped (this script would be very much simpler if they weren't).
HTML:
<input type="button" id='create' value="Create div!"/>
JS:
var i = 0;
document.onclick = function(e) {
var t = e.target;
if(t.id == 'create'){
t.parentNode.innerHTML += '<div>I AM A CHILD '+(++i)+' <input type="button" class="child" value="DELETE ME!"/><br/></div>';
}
if (t.className == 'child') {
t.parentNode.outerHTML = '';
}
};
using document.onclick and detecting the target element can be used as a live click to monitor newly created divs.
Its early and my brain may be a little foggy and the code may be a little dirty
Here is a jsfiddle

Categories