pass/propagate event.target of parent element [duplicate] - javascript

I am trying to change the innerHTML of my page to become the innerHTML of the element I click on, the only problem is that i want it to take the whole element such as:
<section class="homeItem" data-detail="{"ID":"8","Name":"MacBook Air","Description":"2015 MacBook A…"20","Price":"899","Photo":"Images/Products/macbookAir.png"}"></section>
Whereas the code that i have written in javascript:
function selectedProduct(event){
target = event.target;
element = document.getElementById("test");
element.innerHTML = target.innerHTML;
}
will target the specific element that i click on.
What i would like to achieve is when i click on anywhere in the <section> element, that it will take the innerHTML of the whole element rather than the specific one that i have clicked.
I would presume it is something to do with selecting the parent element of the one that is clicked but i am not sure and can't find anything online.
If possible i would like to stay away from JQuery

I think what you need is to use the event.currentTarget. This will contain the element that actually has the event listener. So if the whole <section> has the eventlistener event.target will be the clicked element, the <section> will be in event.currentTarget.
Otherwise parentNode might be what you're looking for.
link to currentTarget
link to parentNode

To use the parent of an element use parentElement:
function selectedProduct(event){
var target = event.target;
var parent = target.parentElement;//parent of "target"
}

handleEvent(e) {
const parent = e.currentTarget.parentNode;
}

function getParent(event)
{
return event.target.parentNode;
}
Examples:
1. document.body.addEventListener("click", getParent, false); returns the parent element of the current element that you have clicked.
If you want to use inside any function then pass your event and call the function like this :
function yourFunction(event){
var parentElement = getParent(event);
}

var _RemoveBtn = document.getElementsByClassName("remove");
for(var i=0 ; i<_RemoveBtn.length ; i++){
_RemoveBtn[i].addEventListener('click',sample,false);
}
function sample(event){
console.log(event.currentTarget.parentNode);
}

$(document).on("click", function(event){
var a = $(event.target).parents();
var flaghide = true;
a.each(function(index, val){
if(val == $(container)[0]){
flaghide = false;
}
});
if(flaghide == true){
//required code
}
})

Related

Select Single DOM Element

I have a eventlistener looking for a click on DOM elements with a certain class, and then changing innerHTML. It works, except it changes the innerHTML on all elements with the same class, and not just the one clicked. Is there a way to limit the scope to the element that was clicked, or do I need to give all the elements their own ID and call them based on IDs?
This is the function that I'm using:
$("button.accordion").click(function(){
if ($(".caretUD").html("▼")) {
$(".caretUD").html("▲");
} else {
console.log("I'm not working...");
}
});
Is that helps ?
this is the current clicked element.
Notice that the event.currentTarget is the element where the event is recorded and this the element who fire the event (can be a child of the event.currentTarget or itself). In your case, with a button, it should be the same.
$("button.accordion").click(function(event) {
if ($(this).html("▼")) {
$(this).html("▲");
} else {
console.log("I'm not working...");
}
});
If .caretUD and button.accordian are both contained with the same container element, what you want is:
$("button.accordion").click(function() {
var caret = $(this).closest(".container").find(".caretUD");
if (caret.html() == "&#9660") {
caret.html("▲");
} else {
console.log("I'm not working");
}
});
Replace .container with the actual class of the element that contains the button and the corresponding caret.
var els = document.getElementsByClassName("button.accordion"); // get all the elements with a certain class
for (var i = 0; i < els.length; i++){
els[i].addEventListener('click',function(e){
e.target.innerHTML = "something"; // e attribute is the key in this solution, as it gets the single DOM element that fired the event
});
}
jQuery solution:
$("button.accordion").click(function(){
if ($(this).html() == "▼") {
$(this).html("▲");
} else {
console.log("I'm not working...");
}
});

Can't get cloned element to keep originals events

I'm trying to clone an element that is passed into a function and all events associated to it, as there are $('.example').on('click', function(e) ... )} events like this defined in document ready.
So I do following:
$('.example').on('click', function(e) {
e.preventDefault();
surpriseMe($(this));
});
and I try to clone this element along side its events here (I need to grab parent as .html() returns only inner html, hence element itself) :
function surpriseMe(element) {
var newElement = element.parent().clone(true,true).html();
surprise.insertBefore(element.parent());
if (numElements == 3) {
newMonth = $('<li class="item-dragable-placeholder">'+ newElement +'</li>
}
}
I believe true, true inside .clone() should force parent also grab its children events, but whenever I click on newly placed element, nothing happens
To use event delegation...
Change:
$('.example').on('click', function(e) { ...
To:
$(document).on('click', '.example', function(e) { ...
Note: Instead of using document, find the closest ancestor element (container) that's available on page load and use that.
when you do your insert, instead of inserting the new element, you ask to insert only the html, remove the html part, it will give you the element and its functionalities.
var newElement = element.parent().clone(true,true).html();
See the following (example)[http://jsfiddle.net/dshun/1j9khfnc/4/](please note, since the example code given is not complete. For example, the variable surprise, numElements are not declared. I made some assumptions in my fiddle)
$(document).ready(function(){
var numElements=0;
function surpriseMe(element) {
var newElement = element.parent().clone(true,true);
newElement.insertBefore( ".inner" );
numElements++;
if (numElements == 3) {
newMonth = $('li.item-dragable-placeholder').insert(newElement);
}
}
$('.example').on('click', function(e) {
e.preventDefault();
surpriseMe($(this));
});
});

Can you target an elements parent element using event.target?

I am trying to change the innerHTML of my page to become the innerHTML of the element I click on, the only problem is that i want it to take the whole element such as:
<section class="homeItem" data-detail="{"ID":"8","Name":"MacBook Air","Description":"2015 MacBook A…"20","Price":"899","Photo":"Images/Products/macbookAir.png"}"></section>
Whereas the code that i have written in javascript:
function selectedProduct(event){
target = event.target;
element = document.getElementById("test");
element.innerHTML = target.innerHTML;
}
will target the specific element that i click on.
What i would like to achieve is when i click on anywhere in the <section> element, that it will take the innerHTML of the whole element rather than the specific one that i have clicked.
I would presume it is something to do with selecting the parent element of the one that is clicked but i am not sure and can't find anything online.
If possible i would like to stay away from JQuery
I think what you need is to use the event.currentTarget. This will contain the element that actually has the event listener. So if the whole <section> has the eventlistener event.target will be the clicked element, the <section> will be in event.currentTarget.
Otherwise parentNode might be what you're looking for.
link to currentTarget
link to parentNode
To use the parent of an element use parentElement:
function selectedProduct(event){
var target = event.target;
var parent = target.parentElement;//parent of "target"
}
handleEvent(e) {
const parent = e.currentTarget.parentNode;
}
function getParent(event)
{
return event.target.parentNode;
}
Examples:
1. document.body.addEventListener("click", getParent, false); returns the parent element of the current element that you have clicked.
If you want to use inside any function then pass your event and call the function like this :
function yourFunction(event){
var parentElement = getParent(event);
}
var _RemoveBtn = document.getElementsByClassName("remove");
for(var i=0 ; i<_RemoveBtn.length ; i++){
_RemoveBtn[i].addEventListener('click',sample,false);
}
function sample(event){
console.log(event.currentTarget.parentNode);
}
$(document).on("click", function(event){
var a = $(event.target).parents();
var flaghide = true;
a.each(function(index, val){
if(val == $(container)[0]){
flaghide = false;
}
});
if(flaghide == true){
//required code
}
})

Click HTML except one element, without using jQuery

I show us the code:
(function (){
var element = document.getElementById('bar'), hideElement = document.getElementById('foo'),
var html = document.getElementsByTagName('html')[0];
tool.onclick = function() {
hideElement.style.display = 'block';
html.onclick = function() {
hideElement.style.display = 'none';
}
}
})();
This piece of code work's fine, but, after clicking html, I can not reopen the hidden element.
I want to click the html element and give display:none to hideElement, then to click the element id="bar", give to the hidden element display:block, but instead of click the element foo, click the html element. What I can do?
Oh, i need help WITHOUT JQUERY, thanks :)
EDIT: something like that : click on body except some other tag not working , but without JQuery,
I'm not sure it's going to answer your question, but here it is: how to handle an event on the body except one element:
document.documentElement.onclick = function(e) {
var evt = e || window.event, // IE...
target = evt.target || evt.srcElement // IE again...
// There, "target" is the element clicked. See where I'm going?
if (target.id !== "foo") {
// Do w/e you want if the page was clicked, except for "foo"
}
}
This is the concept of "event bubbling". You can listen to one element and all its children at once, and get the target as specified in the code up there.
First, you don't appear to be defining tool anywhere that I can see.
Second, you forgot .style in hideElement.display (should be hideElement.style.display).
Third, document.getElementsByTagName('html')[0] is redundant. Just use document.documentElement instead.
Change
html.onclick = function() {
hideElement.display = 'none';
}
to
html.onclick = function() {
hideElement.style.display = 'none';
}

How to get the element clicked (for the whole document)?

I would like to get the current element (whatever element that is) in an HTML document that I clicked. I am using:
$(document).click(function () {
alert($(this).text());
});
But very strangely, I get the text of the whole(!) document, not the clicked element.
How to get only the element I clicked on?
Example
<body>
<div class="myclass">test</div>
<p>asdfasfasf</p>
</body>
If I click on the "test" text, I would like to be able to read the attribute with $(this).attr("myclass") in jQuery.
You need to use the event.target which is the element which originally triggered the event. The this in your example code refers to document.
In jQuery, that's...
$(document).click(function(event) {
var text = $(event.target).text();
});
Without jQuery...
document.addEventListener('click', function(e) {
e = e || window.event;
var target = e.target || e.srcElement,
text = target.textContent || target.innerText;
}, false);
Also, ensure if you need to support < IE9 that you use attachEvent() instead of addEventListener().
event.target to get the element
window.onclick = e => {
console.log(e.target); // to get the element
console.log(e.target.tagName); // to get the element tag name alone
}
to get the text from clicked element
window.onclick = e => {
console.log(e.target.innerText);
}
use the following inside the body tag
<body onclick="theFunction(event)">
then use in javascript the following function to get the ID
<script>
function theFunction(e)
{ alert(e.target.id);}
You can find the target element in event.target:
$(document).click(function(event) {
console.log($(event.target).text());
});
References:
http://api.jquery.com/event.target/
Use delegate and event.target. delegate takes advantage of the event bubbling by letting one element listen for, and handle, events on child elements. target is the jQ-normalized property of the event object representing the object from which the event originated.
$(document).delegate('*', 'click', function (event) {
// event.target is the element
// $(event.target).text() gets its text
});
Demo: http://jsfiddle.net/xXTbP/
I know this post is really old but, to get the contents of an element in reference to its ID, this is what I would do:
window.onclick = e => {
console.log(e.target);
console.log(e.target.id, ' -->', e.target.innerHTML);
}
This is the esiest way to get clicked element in javascript.
window.addEventListener('click', (e) => console.log(e.target));
$(document).click(function (e) {
alert($(e.target).text());
});
pass "this" as argument when you call the function:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<span onclick="click_here(this);">clicked</span>
<script>
function click_here(elmnt){
alert($(elmnt).text());
}
</script>
Here's a solution that uses a jQuery selector so you can easily target tags of any class, ID, type etc.
jQuery('div').on('click', function(){
var node = jQuery(this).get(0);
var range = document.createRange();
range.selectNodeContents( node );
window.getSelection().removeAllRanges();
window.getSelection().addRange( range );
});

Categories

Resources