I am having issues with onclick events triggered on parent elements but not on children.
I have an image grid created through JavaScript:
HTML div:
JavaScript to append images to this image-grid div:
var columnDiv = document.createElement('div');
columnDiv.setAttribute('class', 'column');
// create content div inside column
var contentDiv = document.createElement('div');
contentDiv.setAttribute('class', 'content');
contentDiv.setAttribute('data-animation_url', element['animation_url'])
contentDiv.setAttribute('data-image_url', element['image_url'])
// create image and append to contentDiv
var image = document.createElement('img');
image.setAttribute('src', image_gateway_url);
image.setAttribute('style', 'width:100%');
contentDiv.appendChild(image);
// add image name
var caption = document.createElement('span');
caption.setAttribute('class', 'image-name')
caption.innerHTML=element['name'];
contentDiv.appendChild(caption);
// append content div to column and append it to the grid
columnDiv.appendChild(contentDiv);
document.getElementById('image-grid').appendChild(columnDiv);
CSS:
#image-grid{
margin: auto;
position:absolute;
z-index: -1;
}
.column {
float: left;
width: 25%;
height: 35vh;
position: relative;
z-index: 0;
}
.content {
background-color: white;
padding: 10px;
position: relative;
z-index: 1;
}
JavaScript code for click event:
$('div').click(function() {
var myClass = this.className;
alert(myClass);
});
When clicking on images, the event triggers the alert 'gallery-grid' wherever I click.
From other posts I would expect the event to trigger on children first then work its way up towards the parent but for some reason it is not the case here...
Does anyone happen to know how I could access the 'content' class div with my onclick event to redirect users to the page relevant to the image they clicked ?
Thank you
The issue was caused by the use of this instead of event.target.
This code now allows to iterate over all parent divs until I find the one I am interested in:
$('div').click(function(event) {
let currentElement = event.target;
while(currentElement.className != 'content') {
currentElement=currentElement.parentNode;
};
alert(currentElement.className);
})
Related
I've got an inventory for items in my javascript game.
I'm trying to make it so that when you mouseover an inventory item it shows a text overlay description of the item.
My idea was to append a div with the mouseover "reveal()" function once the item is added to the inventory but for some reason its not working. It works with the item text being ::before or ::after the div but i cant seem to get a text overlay of the item image even when playing around with the Z-Index.etc
I've tried a simple :hover in CSS but couldnt get it to work that way either.
I can "spawn" the item with the text on top from the start i just cant seem to get it so that the text only appears on a mouse over.
Hopefully i have explained it in a way that makes sense:
const textElement = document.getElementById('text');
const imgElement = document.getElementById('room-image');
const optionButtonsElement = document.getElementById('option-buttons');
const button3 = document.getElementById('TEST');
const inventory = document.getElementById('inventory');
const itemContainer = document.getElementById('imageContainer');
const itemText = document.getElementById('itemtext');
let textArrayIteration = 1
function reveal() {
itemText.classList.toggle('on');
}
//ADDING OBJECT VALUE TO INVENTORY///
function pullValue() {
var node = document.createElement("P");
var textNodeItems = Object.values(items);
var textNode = (document.createTextNode(textNodeItems));
node.appendChild(textNode);
document.getElementById("inventory").appendChild(node);
//ASSIGNING THE IMAGE AND DIVS FOR THE ITEM//
if (inventory.innerHTML.indexOf("test") !== -1) {
var a = document.createElement("div")
a.setAttribute("id", "Div1");
var iconUrl = document.createElement("img");
iconUrl.src = "test.jpg";
a.appendChild(itemText);
a.appendChild(iconUrl);
inventory.appendChild(a);
node.style.display = "none";
}
.itemtext-on {
position: absolute;
display: none;
z-index: 200;
}
.itemtext {
position: absolute;
display: block;
font-size: 80px;
top: 50px;
color: red;
z-index: 200;
}
<div id="itemtext" class="itemtext" onmouseover="reveal()">test</div>
You have not defined the class on.
I see that you have defined .itemtext-on.
If this is a typo, then change it to .itemtext.on and it should work.
I'm trying to add a link to a pseudo element, but not the parent element. I'm brand new to javascript, and after doing a lot of research I've been able to add a link to both the parent and pseudo elements, but I don't want the parent to be linked. It unfortunately will have to be a pseudo element because I don't have the option of adding another div to the html.
I have a fiddle which is kind of a mash of a few different fiddles I've found. Please let me know if I'm on the right track, or if this is even possible. And let me know if there is any additional information I can provide.
One more thing to note, is that the parent div will have child divs as a menu, which is why I'd prefer the parent not be clickable. But after testing (at least in the fiddle as it is now) the child links are still be clickable and correct, and these will still need to be clickable as well.
Thanks!
http://jsfiddle.net/mqb9juhn/1/
<div id="example">
<div class="example-child">
Test Test 2
</div>
</div>
#example {
position: relative;
}
#example::before {
content: "click here"!important;
font-size: 16px;
display: block;
padding: 20px;
background-color: #ffff00;
top: 0;
}
var UID = {
_current: 0,
getNew: function(){
this._current++;
return this._current;
}
};
HTMLElement.prototype.pseudoStyle = function(element,prop,value){
var _this = this;
var _sheetId = "pseudoStyles";
var _head = document.head || document.getElementsByTagName('head')[0];
var _sheet = document.getElementById(_sheetId) || document.createElement('style');
_sheet.id = _sheetId;
var className = "pseudoStyle" + UID.getNew();
_this.className += " "+className;
_sheet.innerHTML += "\n."+className+":"+element+"{"+prop+":"+value+"}";
_head.appendChild(_sheet);
return this;
};
$(document).ready(function(){ $("#example").on('click', function(){
window.location = "http://www.google.com/";});
});
var div = document.getElementById("example");
div.pseudoStyle("before","color","#ff0000");
I created 3 radio buttons and a label for each of them using JavaScript. When I try adding for in the label using htmlFor, it doesn't apply it to the actual DOM Element. Meaning, when I try using the label on the webpage, it doesn't select the radio button.
I checked in the developer tools, and saw that the labels did not have for applied to them.
What am I doing wrong, and how can I fix it?
JSFiddle
var _doc = document,
sliderWrapper = _doc.getElementById('sliderWrapper'),
radioWrapper = _doc.createElement('div');
for (var i = 0; i < 3; i++) {
var radio = _doc.createElement('input');
var niceRadio = _doc.createElement('lable');
var index = radioWrapper.children.length / 2;
niceRadio.className = 'niceRadio';
niceRadio.htmlFor = radio.id = 'sliderRadio' + index;
radio.type = 'radio';
radio.name = 'myName';
radioWrapper.appendChild(radio);
radioWrapper.appendChild(niceRadio);
console.log(niceRadio.htmlFor);
}
sliderWrapper.appendChild(radioWrapper);
.niceRadio {
position: relative;
width: 20px;
height: 20px;
cursor: pointer;
border-radius: 50%;
border: 5px solid orange;
}
.niceRadio:hover {
border-color: lightblue;
}
<div id="sliderWrapper">
</div>
The htmlFor is used to bind a label to a specific form element. However, it uses the id of that form element (not the name).
Source MDN:
The HTMLLabelElement.htmlFor property reflects the value of the for
content property. That means that this script-accessible property is
used to set and read the value of the content property for, which is
the ID of the label's associated control element.
Also, in your fiddle, you misspelled label.
Updated fiddle: https://jsfiddle.net/h09mm827/2/
I've created a sample file that has adding and removing children elements in a mother element. The adding was successful, but I'm having a problem in removing children elements. The goal is every single click of remove button removes a child element.
var adds = document.querySelector('#add');
var remove = document.querySelector('#remove');
var section = document.querySelector('section');
var div;
adds.onclick = function() {
div = document.createElement('div');
section.appendChild(div);
div.classList.add('style');
};
// THE PROBLEM
remove.onclick = function() {
while(section.children.length !== 0) {
for(var c in section.children) {
section.removeChild(div[c]);
}
}
};
section {
display: flex;
background: #0ff;
height: 100px;
padding: 8px;
}
section > div {margin: 0 1px;}
.style {
width: 100px;
height: 100px;
background: lightgreen;
}
<button id="add">Add</button>
<button id="remove">Remove</button>
<section class="container"></section>
<br>
What's wrong with my code?
What's wrong with my code?
This line
section.removeChild(div[c]);
div could be undefined here and anyways, sections's children are not necessarily div's children
so change it to
section.removeChild(section.children [c]);
Also, while is not necessary
remove.onclick = function() {
for(var c in section.children) {
section.removeChild(section.children[c]);
}
};
EDIT
The goal is every single click of remove button removes a child
element.
remove.onclick = function() {
if(section.children length ) {
section.removeChild(section.children[0]);
}
};
changed for with if
So I have a div (with the id of "thecolor2") that I want to append to an unordered list, but before I append it, I want to set its background color to a variable which has the value of a hex code. However, for some reason, it doesn't take in the color.
Here is the CSS:
#thecolor2{
height: 50px;
width: 50px;
border-radius: 100px;
border: 1px solid yellow;
position: relative;
bottom: 635px;
}
Her is the HTML:
<ul id = "allposts"></ul>
And here is the JS:
var thestream = document.getElementById('allposts');
var oneofpost = document.createElement('li');
var thecolor2 = document.createElement('div');
thecolor2.id = "thecolor2";
$("#thecolor2").css("background-color", color);
thestream.appendChild(oneofpost);
thestream.appendChild(thecolor2);
You cant use a jQuery ID selector to match a node which hasn't been added to the document tree. You can simply use plain DOM to set its inline CSS style like this:
thecolor2.style.backgroundColor = color
As described by Carlo in another answer, you cannot use the jQuery selector to select elements that haven't been added. You can however, turn a created DOM element into a jQuery object by doing:
var thecolor2 = $(document.createElement('div'));
However, if you're going to be using jQuery then I suggest writing everything in jQuery, otherwise stick with using pure JavaScript for everything.
jQuery
var thestream = $('#allposts');
var oneofpost = $('<li></li>');
var thecolor2 = $('<div></div>');
thecolor2.prop('id', "thecolor2")
.css({
backgroundColor: color
}).appendTo(oneofpost);
thestream.append(oneofpost);
See jsFiddle
JavaScript
var thestream = document.getElementById('allposts');
var oneofpost = document.createElement('li');
var thecolor2 = document.createElement('div');
thecolor2.id = "thecolor2";
thecolor2.style.backgroundColor = color;
oneofpost.appendChild(thecolor2);
thestream.appendChild(oneofpost);
See jsFiddle
Also I'm assuming you're trying to append a list item to the ul, so I corrected the code you had there with appendChild.