Can you target an elements parent element using event.target? - 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

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

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
}
})

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));
});
});

Adding an Event via jQuery to newly created DOM Element

I am trying to assign an event to a newly created DOM Element:
var Element = document.createElement("div");
$(document).on('click',Element,function() {
console.log("B");
});
After executing this code and clicking on the newly created div, nothing happens.
Any idea why?
I have also tried:
var Element = document.createElement("div");
$(Element).click(function(event) {
console.log("B");
});
You need to add the element to the DOM before it will receive events.
Here's one way to do it:
var $div = $('<div>')
.text('Click Me!')
.on('click', function() {
alert('Clicked!');
});
$(document.body).append($div);
// Now you can click on it and see the alert.
Since you're using jQuery...
var Element = $("<div/>").click(function() {console.log("B");}).appendTo('body');
Of course, append it where you need it...
Just bind your event on the body and pass your selector in parameter like this:
$('body').on('click','.foo',function() {
console.log("B");
});
var Element = document.createElement("div").className = "foo";
Here the codepen :
http://codepen.io/anon/pen/xvLqo

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';
}

Categories

Resources